C++ programming language provides flexibility to specify a default value for function arguments. We have to specify the default value of the function arguments during function declaration.
- It is not compulsory to specify default values for all arguments, but if you provide default value for an argument X, then You must provide default values for each argument after X otherwise program will not compile.
- A function with three parameters may be called with only two parameters. For this, the function declaration must include a default value for third(last) parameter, which will be used by the function when calling function passes fewer arguments.
int getSum(int A, int B = 10){ return A + B; }
Calling function can call getSum function by either passing one or two parameters.
int sum = getSum(5); // Calling by passing only one argument.
Here, calling function is only passing value for formal parameter A(which is 5) and parameter B will take default value which is 10. Hence, the value of sum will be 15.
int sum = getSum(5, 6); // Calling by passing two argument.
Here, calling function is passing value for both parameters A and B. Both A and B will contain the actual parameters passed by the calling. In this case function will not use the default value for argument B. Hence, the value of sum will be 11.
int sum = getSum(5, 6); // Calling by passing two argument.
- If a value for that parameter is not passed when the function is called, the default given specified for that parameter will be used.
- If a value of a parameter is passed will calling a function then the default value is ignored and the passed value is used.
C++ Function Default Argument Example Program
#include <iostream> using namespace std; // Default value for B is 10 int getsum(int A, int B=10) { return A + B; } int main () { int sum; // Passing values for both arguments, // B will not take the default value sum = getsum(5, 6); cout << "Sum = " << sum << endl; // Passing value only for one parameter(A) // B will take the default of 10 sum = getsum(5); cout << "Sum = " << sum << endl; return 0; }
Output
Sum = 11 Sum = 15In above program, we defined a function called getSum with two input parameters A and B. We have assigned default value of 10 to parameter B. In main, we first call getSum function with two arguments as getsum(5, 6);. In this case, formal parameters A and B takes 5 and 6 respectively. In second call to getSum function, we pass only one argument getsum(5);. In this case, formal parameter A becomes 5 and B takes default value which is 10.