The value that is provided in the declaration of the function itself is called a default argument.
These default values are assigned automatically to the function by the compiler.
We will look into the sample program below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include<iostream> using namespace std; int Add (int val1, int val2, int x=0, int y=0) { return (val1 + val2 + x + y); } int main() { cout << Add(10, 15) << endl; cout << Add(10, 15, 25) << endl; cout << Add(10, 10, 10, 10) << endl; return 0; } |
In the above program there is no need to write 3 sum functions, only one function works by using default values for 3rd and 4th arguments.
Output of the above program is:
1 2 3 4 5 |
25 50 40 |
The default arguments should pass like all subsequent arguments must have default value.
1 2 3 |
int Add (int val1, int val2, int x=0, int y=0); // valid int Add (int val1, int val2, int x=0, int y); // not valid |