Function part 9 (Default arguments)

Estimated reading: 2 minutes 159 Views

Default arguments are a feature of C++ that allows you to specify a default value for a function parameter. This means that if a caller of the function does not provide a value for a particular parameter, the default value will be used instead.

Default arguments can be useful for simplifying the code that calls a function, and for making the function more flexible. For example, you could have a function that takes two parameters, but where the second parameter is optional. You could then specify a default value for the second parameter, so that callers of the function do not have to provide a value for it if they do not want to.

Here is an example of how to use default arguments in C++:

#include <iostream>
using namespace std;

int sum(int a = 5, int b = 5, int c = 5)
{
    return a + b + c;
}

int main()
{
    cout << sum(10, 55) << endl;
    return 0;
}

This code calculates the sum of three integers. The program uses default arguments to provide default values for the three integers. This means that if the caller of the sum() function does not provide values for all three integers, the default values will be used instead.

The main() function calls the sum() function with the arguments 10 and 55. The sum() function will then return the sum of the three integers, which is 70. The main() function will then print the result to the console.

Output:

70

Here are some tips for using default arguments:

  • Do not write your default argument in the middle of two arguments like this (int a, int b = 5, int c), it will produce an error to the compiler.
  • Be careful not to overwrite default parameters with values that are not valid for the function.
  • Use default parameters to provide default values for parameters that are not essential to the function’s functionality.
Share this

Function part 9 (Default arguments)

Or copy link

CONTENTS
English