Default parameters: Specify the default value of the parameter in the function definition, use constant predefined; variable parameters: Use ellipses to indicate, compile to a pointer to the array, package the incoming parameters, traverse the array to access the parameters.
Explore the underlying implementation of default parameters and variable parameters of C functions
Default parameters
Default parameters are a mechanism by which parameter default values can be specified in function definitions. It allows functions to use default values when no actual parameters are passed.
Under the hood, default parameters are actually implemented by the compiler, that is, parameters that are predefined as constants. When the compiler calls a function with default parameters, it checks if the incoming variable is passed, and if not, it uses the predefined default value.
For example:
void print_number(int num, int default_num = 10) { cout << (num ? num : default_num) << endl; }
When calling this function, we can pass or not pass the second parameter:
print_number(5); // 输出 5 print_number(0, 20); // 输出 20
Variable parameters
Variable parameters are also called variable-length parameters, which allow functions to accept an indefinite number of parameters. In C, varargs are represented by ellipses (...
).
Under the hood, variadic parameters are compiled into a pointer to an array. When the function is called, the compiler packs the passed arguments into this allocated array. The function can then iterate over the array to access the parameters.
For example:
int sum_numbers(int count, ...) { int sum = 0; va_list args; va_start(args, count); // 获取可变参数列表 for (int i = 0; i < count; ++i) { sum += va_arg(args, int); // 访问第 i 个参数 } va_end(args); // 清理可变参数列表 return sum; }
When calling this function, we can pass any number of parameters:
cout << sum_numbers(3, 1, 2, 3) << endl; // 输出 6 cout << sum_numbers(5, 10, 20, 30, 40, 50) << endl; // 输出 150
Practical case
In the real world, default parameters and variable parameters have a wide range of applications. For example:
print()
function in Python. The above is the detailed content of Explore the underlying implementation of default parameters and variable parameters of C++ functions. For more information, please follow other related articles on the PHP Chinese website!