In this article we are going to learn about default arguments or parameters in C++.
In C++ when you define a function you can assign default value to the function parameters or arguments. A default argument is a value assigned by the compiler itself if the caller of the function forgets to enter value to the function parameter.
However, if the argument is passed in the function then the default arguments are ignored and the passed argument is treated as actual arguments.
We can understand the working of default arguments from the image above :
temp() is called, both the default parameters are used by the function.
temp(6) is called, the first argument becomes 6 while the default value is used
for the second parameter.
temp(6, -2.3) is called, both the default parameters are overridden,
resulting in i = 6 and f = -2.3.
temp(3.4) is passed, the function behaves in an undesired way
because the second argument cannot be passed without passing the first.
argument.
Therefore, 3.4 is passed as the first argument. Since the first argument has
been defined as int, the value that is actually passed is 3.
Important Point : Keep in mind the default value is always assigned from right to left that is in above example you cannot assign a default value to int unless and until you have assigned the default value for float.
Example : Default argument
#include <iostream>
using namespace std;
// defining the default arguments
// we cannot assign value to char before assigning value to int.
void example(char = '$', int = 9);
int main() {
int test = 6;
cout
Output :
No argument passed: $$$$$$$$$
First argument passed: #########
Both arguments passed: &&&&&&
Explanation for above program:
-
In first case when
example() was called without passing any arguments. The
compiler itself called the default parameters c = '*' and test = 9 of
function example().
-
In second case when
example('#') was called with only one argument. The
first parameter becomes '#'. The second default parameter test = 9 is
retained.
-
In third case when
example('&', test) was called with both arguments. In this
case, default arguments are not used.
We can also define the default parameters in the function definition
itself.
Things to Remember :
-
Once we provide a default value for a parameter, all subsequent
parameters must also have default values. For example,
// Invalid
void add(int x, int y = 3, int z, int m);
// Invalid
void add(int x, int y = 3, int z, int m = 4);
// Valid
void add(int x, int y, int z = 3, int m = 4);
-
If we are defining the default arguments in the function definition instead
of the function prototype, then the function must be defined before the
function call.
// Invalid code
int main() {
// function call
example();
}
void example(char c = '$', int test = 9) {
// code
}