CPP Default Arguments in C++

Default Arguments in C++

  • A default argument is a value provided in function declaration that is automatically assigned by the compiler if caller of the function doesn’t provide a value for the argument with default value.
  • Following is a simple C++ example to demonstrate use of default arguments. We don’t have to write 3 sum functions, only one function works by using default values for 3rd and 4th arguments.



// A function with default arguments, it can be called with 
// 2 arguments or 3 arguments or 4 arguments.
int sum(int x, int y, int z=0, int w=0)
    return (x + y + z + w);

/* Drier program to test above function*/
void main()
    cout << sum(10, 15) << endl;
    cout << sum(10, 15, 25) << endl;
    cout << sum(10, 15, 25, 30) << endl;



Share This Page on:

Ask Question