Default argument values

Location
  1. Courses

    /

  2. Complete C++ Course

    /

  3. The basics

    /

  4. Default argument values

Giving default values to parameters

It is possible to assign, at the declaration or definition of a function (Not both), default values to its arguments. In case one or many of those arguments do not receive values when the function is called, the default values are used. It is done by simply adding, inside the parentheses () of the function declaration or definition, an equal sign = after the name of the argument, followed by the value.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream> int func(int a = 5, int b = 6) { return a*b; } int main() { std::cout << func() << std::endl; // 30 is printed in the console. std::cout << func(1) << std::endl; // 6 is printed in the console. std::cout << func(2, 4) << std::endl; // 8 is printed in the console. return 0; }

Note that, when we call a function, it is not possible to give the value of an argument without giving the values of the arguments before it. For example, in the code above, it is not possible, when we call the function func, to give the value of the parameter b without giving the value of a.

In the declaration or definition, not both

Only either the declaration (If there is one) or the definition of the function may specify the default values. Otherwise it causes an error:

int func(int a = 5, int b = 6); int func(int a = 5, int b = 6) // Error: Default values already defined in the declaration. { return a*b; }

The following works:

int func(int a, int b); int func(int a = 5, int b = 6) { return a*b; }

And the following too:

int func(int a = 5, int b = 6); int func(int a, int b) { return a*b; }

Setting the default value of some arguments

We do not have to set default values to all the arguments:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream> int func(int a, int b = 6) { return a*b; } int main() { std::cout << func(4) << std::endl; // 24 is printed in the console. return 0; }

However, if we set a default value to an argument, parameters that follow it must have one too.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int func(int a=4, int b) // Error. If the argument a has a default value, b must have one too. { return a*6; } int func2(int a, int b=4, int c) // Error. If b has a default value, c must have one too. { return a*b*c; } int func3(int a, int b=4, int c=5) // Here it works. { return a*b/c; }

Note that giving default values to arguments is only possible in C++, not C.