C++ Default Arguments (Parameters)

In C++, default arguments allow a function to have default values for one or more of its parameters. If a value is not provided for a particular parameter, the default value is used instead. This can be useful for reducing the number of different versions of a function that need to be written.

Example:

1#include <iostream> 2using namespace std; 3 4void printNum(int num1, int num2 = 20) 5{ 6 cout << "Number 1: " << num1 << endl; 7 cout << "Number 2: " << num2 << endl; 8} 9 10int main() 11{ 12 printNum(10); 13 printNum(30, 40); 14 15 return 0; 16}

Output:

1Number 1: 10 2Number 2: 20 3Number 1: 30 4Number 2: 40

It is important to note that default arguments must be declared at the end of the function parameter list. This means that all parameters before the default argument must have a value specified when the function is called.

In addition, default arguments are evaluated only once, at the point of function declaration. This means that if the default argument is a variable or a function, its value will be the same for every call to the function.

Example:

1#include <iostream> 2using namespace std; 3 4int counter = 0; 5 6void printNum(int num1, int num2 = counter++) 7{ 8 cout << "Number 1: " << num1 << endl; 9 cout << "Number 2: " << num2 << endl; 10} 11 12int main() 13{ 14 printNum(10); 15 printNum(30); 16 printNum(50); 17 18 return 0; 19}

Output:

1Number 1: 10 2Number 2: 0 3Number 1: 30 4Number 2: 0 5Number 1: 50 6Number 2: 0