English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C++ Default parameters (actual parameters)

In this article, you will learn what default parameters are, how to use them, and the necessary declarations for using them.

In C ++In programming, you can provideFunctionDefault parameter values.

The idea behind default parameters is very simple. If the function is called by passing parameters, then these parameters will be used by the function.

However, if no parameters are passed when calling the function, the default values are used.

Default values are passed to the parameters in the function prototype.

How default parameters work

Example: Default parameters

// c++Program demonstrates how default parameters work
#include <iostream>
using namespace std;
void display(char = '*', int = 1);
int main()
{
    cout << "\nNo parameters are passed:\n";
    display();
    
    
    display('#');
    
    cout << "\nTwo parameters are passed:\n";
    display('$', 5);
    return 0;
}
void display(char c, int n)
{
    for(int i = 1; i <= n; ++i)
    {
        cout << c;
    }
    cout << endl;
}

Output result

No parameters are passed:
*
The first parameter is passed:
#
Two parameters are passed:
$$$$$

In the above program, you can see that assigning default values to parameters void display(char ='*',int = 1);

Firstly, call the function without passing any parameters to display(). In this case, the display() function uses the default parameter c = *and n = 1.

Then, when the function is called for the second time, only the first parameter is passed. In this case, the function does not use the first default value passed. It uses the actual parameter c = # passed as the first parameter, and the default value n = 1as the second parameter.

When the third call to display() is made, two parameters are passed, neither of which uses the default parameter. The values passed are c = $ and n = 5.

Common mistakes when using default parameters

  1. void add(int a, int b = 3, int c, int d = 4);
    The above function will not compile. You cannot skip the default parameter between two parameters.
    In this case, c should also be assigned a default value.
     

  2. void add(int a, int b = 3, int c, int d);
    The function above will not compile. You must provide a default value for each parameter after b.
    In this case, c and d should also be assigned default values.
    If you only need one default parameter, make sure that the parameter is the last one. For example: void add(int a, int b, int c, int d = 4);
     

  3. If your function performs multiple operations or the logic looks too complex, you can use  Function OverloadingBetter separation of logic.

  4. No matter how you use default parameters, you should always write a function that serves only one purpose.