• Home
  • What are the default arguments in C++?

What are the default arguments in C++?

In C++, default arguments are function parameters that are given a default value in the function declaration. This means that if a caller of the function does not provide a value for the default argument, the default value will be used instead. For example:

int add(int x, int y=5) // y is a default argument with a default value of 5
return x+y;

In this example, the function “add” takes two integer arguments, x and y. If a caller does not provide a value for y when calling the function, the default value of 5 will be used for y. However, if a value is provided for y, that value will be used instead of the default value.

To specify default arguments in a function declaration, you simply need to include the default value in the function parameter list, like this:

int foo(int x=5, int y=10) // x and y are both default arguments
// function body goes here

When calling a function with default arguments, you can choose to either provide values for all of the arguments, or omit some of the arguments and use the default values. For example:

foo(); // uses default values for x and y (5 and 10, respectively)
foo(7); // uses 7 for x and the default value of 10 for y
foo(7, 8); // uses 7 for x and 8 for y, ignoring the default values

Using default arguments can be a convenient way to reduce the number of function overloads that you need to create, and can also make your code more readable by reducing the number of parameters that a caller needs to provide when calling the function.