Default Arguments in C++
Default Arguments in C++
Example of default argument in C++
Void function(int a, int b, int c = 0)
Explanation – Here the function is valid. The c is defined as a part of the default argument.
Void function(int a, int c = 0, int b)
Explanation – Here also the function is invalid. And c is the value defined in between a and b, and it is not accepted.
Program of default argument in C++
#include <iostream> using namespace std; int mul(int a, int b, int c = 0, int d = 0) { return (a * b * c * d); } int main() { // Statement 1 cout << mul(2, 3) << endl; // Statement 2 cout << mul(2, 3, 4) << endl; // Statement 3 cout << mul(2, 3, 4, 5) << endl; return 0; }
Output
6 24 120
Characteristics of defining the default arguments
- The values to be passed in the default arguments are not constant.
- The values are copied from left to right, during calling the function.
- All the values will be given default value will be on the right.
Advantages of default Arguments
- Default arguments are useful when we want to increase the ability of an existing function by adding another default arguments.
- Default arguments helps in reducing the size of program.
- It improves the consistency of program.
Disadvantages of Default Arguments
Default argumnets increase the execution time as compiler need to replace the leaved out the arguments by there default values in the function call.
Read more, Function Overloading in C++