Search

8.12 — Default arguments

A default argument is a default value provided for a function parameter. For example:

When making a function call, the caller can optionally provide an argument for any function parameter that has a default argument. If the caller provides an argument, the value of the argument in the function call is used. If the caller does not provide an argument, the value of the default argument is used.

Consider the following program:

This program produces the following output:

x: 1
y: 2
x: 3
y: 4

In the first function call, the caller supplied explicit arguments for both parameters, so those argument values are used. In the second function call, the caller omitted the second argument, so the default value of 4 was used.

When to use default arguments

Default arguments are an excellent option when a function needs a value that has a reasonable default value, but for which you want to let the caller override if they wish.

For example, here are a couple of function prototypes for which default arguments might be commonly used:

Author's note

Because the user can choose whether to supply a specific argument value or use the default value, a parameter with a default value provided is sometimes called an optional parameter. However, the term optional parameter is also used to refer to several other types of parameters (including parameters passed by address, and parameters using std::optional), so we recommend avoiding this term.

Multiple default arguments

A function can have multiple parameters with default arguments:

The following output is produced:

Values: 1 2 3
Values: 1 2 30
Values: 1 20 30
Values: 10 20 30

C++ does not (as of C++20) support a function call syntax such as print(,,3) (as a way to provide an explicit value for z while using the default arguments for x and y. This has two major consequences:

1) Default arguments can only be supplied for the rightmost parameters. The following is not allowed:

Rule

Default arguments can only be provided for the rightmost parameters.

2) If more than one default argument exists, the leftmost default argument should be the one most likely to be explicitly set by the user.

Default arguments can only be declared once

Once declared, a default argument can not be redeclared. That means for a function with a forward declaration and a function definition, the default argument can be declared in either the forward declaration or the function definition, but not both.

Best practice is to declare the default argument in the forward declaration and not in the function definition, as the forward declaration is more likely to be seen by other files (particularly if it’s in a header file).

in foo.h:

in main.cpp:

Note that in the above example, we’re able to use the default argument for function print() because main.cpp #includes foo.h, which has the forward declaration that defines the default argument.

Best practice

If the function has a forward declaration (especially one in a header file), put the default argument there. Otherwise, put the default argument in the function definition.

Default arguments and function overloading

Functions with default arguments may be overloaded. For example, the following is allowed:

The function call to print() acts as if the user had explicitly called print(' '), which resolves to print(char).

Now consider this case:

Parameters with default values will differentiate a function overload (meaning the above will compile).
However, such functions can lead to potentially ambiguous function calls. For example:

In the last case, the compiler is unable to tell whether print(1) should resolve to print(int) or one of the two function calls where the second parameter has a default value. The result is an ambiguous function call.

Summary

Default arguments provide a useful mechanism to specify values for parameters that the user may or may not want to override. They are frequently used in C++, and you’ll see them a lot in future lessons.


8.13 -- Function templates
Index
8.11 -- Overloaded function resolution

11 comments to 8.12 — Default arguments

  • kekie

    Shouldn't they be called 'Default arguments'?

  • Sphingine

    Can i give d definition as:

    void printvalues(int nvalue1=0, int nvalue2=2)
    {

    cout<<"1st : "<< nvalue1<< endl;
    cout<<"2st : "<< nvalue2<< endl;

    }

    and call the function as:

    printvalues(,3);

  • otocan

    Hi Alex

    Shouldn't all the examples of pointers to chars in this chapter e.g.

    char *strValue

    be instead

    char *pszValue?

    Cheers

    Kevin

  • dave

    I must say this site is awesome and clean looking..specially how the code is displayed....looks neat! keep up good work and i am doing last min craming when i googled default params...so wish me luck! :)

  • simon1122

    hi

    can any one tell me what is wrong with this one??

    thak you

    • Anshuman

      you must not use specify the default value both in function prototype and definition

      void printvalues(int nvalue1, int nvalue2)
      {
      
      cout<<"1st : "<< nvalue1<< endl;
      cout<<"2st : "<< nvalue2<< endl;
      
      }
      
  • simon1122

    //Function
    #include
    using namespace std;

    void printvalues(int nvalue1, int nvalue2=10 );

    int main()
    {

    printvalues(1);
    printvalues(1,3);

    /*scaffolding code for testing purpose*/
    cin.ignore(256, '\n');
    cout<< "press Enter to continue.." << endl;
    cin.get();

    return 0;
    }

    void printvalues(int nvalue1, int nvalue2 = 10 )
    {

    cout<<"1st : "<< nvalue1<< endl;
    cout<<"2st : "<< nvalue2<< endl;

    }

  • Ericc

    u forgot ; in the Prototype

  • Pathik

    how do you get a random value in C++?
    For example :

    int main()
    {
    	using namespace std;
    	int y = 25; // I want y to be a random number below 100
    	int x;
    	
    try_again:
    	do
    	{
    		cout << "Enter a value below 100: ";
    		cin >> x;
    	}while (x > 100);
    	
    	if (x < y)
    	{
    		cout << "Too small" << endl;
    		goto try_again;
    	}
    	if (x > y)
    	{
    		cout << "Too big" << endl;
    		goto try_again;
    	}
    	if (x == y)
    	{
    		cout << "WOW!! You Got it!" << endl;
    	}
    	return 0;
    }
    

    You see, I want y to be a random number when program starts up.

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">