📅 2020-Jan-01 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ cpp, default arguments ⬩ 📚 Archive
Functions in C++ can be declared with default arguments for one, more or all parameters. This allows the caller the option of not having to specify these arguments in a function call. When the caller does not specify arguments for these parameters, the default arguments are used instead.
For example:
void foobar(int x, int y)
{// ...
}
void foobar(int = 10, int = 20);
int main()
{99, 99);
foobar(99); // Same as foobar(99, 20);
foobar(// Same as foobar(10, 20);
foobar(); return 0;
}
Default arguments should be specified in the function declaration if the declaration exists, and not in the function definition. When there is no function declaration, default arguments can be specified in the function definition.
Default arguments are allowed only for trailing parameters.
Multiple function declarations with default arguments are allowed, as long as each provides a default arguments for a different set of parameters. So, for a function defined with N
parameters, there are N
possible default argument function declarations. For example:
void foobar(int x, int y, int z, int w)
{// ...
}
void foobar(int = 1, int = 2, int = 3, int = 4);
void foobar(int, int = 20, int = 30, int = 40);
void foobar(int, int, int = 300, int = 400);
void foobar(int, int, int, int = 4000);
The compiler generates a single copy of the code for a function definition, no matter how many possible function declarations with differing sets of default arguments are available for that function. So, the existence of default arguments has no effect on the code generated by the compiler for a function definition. The code that is generated assumes that arguments are set for all the parameters of the function by the caller.
Default arguments are handled by the compiler at the call site. If the user has not provided arguments for one or more of the trailing parameters of the function, then the compiler examines the available function declarations and picks the appropriate arguments for every one of the function parameters. Thus the compiler sets all these arguments at the call site and then calls the function.
For example, consider this code:
void foobar(int x = 99)
{
}
int main()
{
foobar(); }
If we generate assembly code, we can see that the default argument 99
is set at the call site before calling the function:
# tmp.cpp:7: foobar();
movl $99, %edi # Set 99 as function argument
call _Z6foobari # Call foobar()
Reference: §8.3.6 Default arguments in the C++11 standard