table of Contents
1. The default function arguments
C ++ can provide a default value for the parameter function declaration , the values did not provide arguments if the function is called, the default value.
The default value of the function parameters can only be specified in the function declaration , no longer appear default value when the function is defined , otherwise the compiler will complain.
//函数声明时指定参数默认值
void func(int x = 0);
//函数定义时不能再指定参数默认值
void func(int x)
{
}
int main()
{
func(); // func(0)
return 0;
}
The default rule function parameters
- The default value of the parameter must be from right to left provided
- When a function call using the default value , then the following parameters also have to use the default values
#include <stdio.h>
int add(int x, int y = 0, int z = 0);
int add(int x, int y, int z)
{
return x + y + z;
}
int main(int argc, char *argv[])
{
printf("%d\n", add(1)); // x = 1, y = 0, z = 0
printf("%d\n", add(1, 2)); // x = 1, y = 2, z = 0
printf("%d\n", add(1, 2, 3)); // x = 1, y = 2, z = 3
return 0;
}
2. placeholder function parameter
It may be provided as a function of positional parameters in C ++
- Placeholder parameters only parameter type declaration , but did not declare the parameter name
- In general, in the functions that can not use the positional parameters
int func(int x, int)
{
return x;
}
//......
func(1, 2); // ok!
Meaning in C ++ function placeholder parameters: placeholder parameters with default parameters used in conjunction with compatible non-standard programs written in C language may arise.
Example 1: C language is not standardized wording
#include <stdio.h>
/*
* 在C语言中,该函数可以接受任意个数、任意类型的参数,
* void func(void)才表示不接受任何参数.
*/
void func()
{
}
int main()
{
func(1);
func(2, 3);
return 0;
}
Example 2: Use positional parameters and default parameters combined with minimal changes, the sample 1 in C ++ code to
#include <stdio.h>
void func(int x, int = 0);
void func(int x, int)
{
}
int main()
{
func(1);
func(2, 3);
return 0;
}