C++ functions: Default Arguments

You can define default values for parameters in a function.

C++ allows you to declare functions with default argument values. The default values are passed to the parameters when a function is invoked without the arguments.

Listing 6.8 demonstrates how to declare functions with default argument values and how to invoke such functions.

Listing 6.8 DefaultArgumentDemo.cpp

1 #include <iostream>
2
using namespace std;
3
4
// Display area of a circle
5 void printArea(double radius = 1)
6 {
7     
double area = radius * radius * 3.14159;
8     cout <<
“area is ” << area << endl;
9 }
10
11
int main()
12 {
13    printArea();
14    printArea(
4);
15
16   
return 0;
17 }

Line 5 declares the printArea function with the parameter radius. radius has a default value 1. Line 13 invokes the function without passing an argument. In this case, the default value 1 is assigned to radius.

When a function contains a mixture of parameters with and without default values, those with default values must be declared last. For example, the following declarations are illegal:

void t1(int x, int y = 0, int z); // Illegal

void t2(int x = 0, int y = 0, int z); // Illegal

However, the following declarations are fine:

void t3(int x, int y = 0, int z = 0); // Legal

void t4(int x = 0, int y = 0, int z = 0); // Legal

When an argument is left out of a function, all arguments that come after it must be left out as well. For example, the following calls are illegal:

t3(1, , 20);

t4(, , 20);

but the following calls are fine:

t3(1); // Parameters y and z are assigned a default value

t4(1, 2); // Parameter z is assigned a default value

Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *