Home > Article > Backend Development > Differences in C++ function default parameters and variable parameters in different compilers
Default parameters allow functions to use default values, supported in C 11 and above, using different syntax in Visual Studio. Variadics allow functions to receive variable arguments. Supported in C 11 and above. Not supported in Visual Studio. Special syntax is required in GCC.
Differences in C function default parameters and variable parameters in different compilers
Default parameters
Default parameters allow functions to use predefined values when the corresponding parameters are not provided. C 11 and later supports default parameters.
In Visual Studio, you can specify default parameters using the following syntax:
int AddNumbers(int a, int b = 10) { return a + b; }
In GCC, use the following syntax:
int AddNumbers(int a, int b = 10) __attribute__((deprecated));
Variable parameters
Variable parameters allow a function to receive an indefinite number of parameters. C 11 and later supports variadic arguments.
In Visual Studio, you can use ...
to represent variable parameters:
void PrintNumbers(int n, ...) { va_list args; va_start(args, n); for (int i = 0; i < n; i++) { cout << va_arg(args, int) << " "; } va_end(args); }
In GCC, use the following syntax:
void PrintNumbers(int n, ...) __attribute__((deprecated));
Actual case
Default parameter case:
int main() { // 使用默认参数 int sum1 = AddNumbers(5); // sum1 为 15 // 不使用默认参数 int sum2 = AddNumbers(5, 20); // sum2 为 25 return 0; }
Variable parameter case:
int main() { // 声明并初始化可变参数列表 int n = 5; int numbers[] = {1, 2, 3, 4, 5}; // 使用可变参数函数打印数字 PrintNumbers(n, numbers); // 输出:1 2 3 4 5 return 0; }
Note
__attribute__((deprecated))
in the default parameter indicates that the feature is deprecated but is still supported. Please use caution when using. The above is the detailed content of Differences in C++ function default parameters and variable parameters in different compilers. For more information, please follow other related articles on the PHP Chinese website!