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.

using namespace std;

// 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*/
int main()
    cout << sum(10, 15) << endl;
    cout << sum(10, 15, 25) << endl;
    cout << sum(10, 15, 25, 30) << endl;
    return 0;



Once default value is used for an argument, all subsequent arguments must have default value.

// Invalid because z has default value, but w after it 
// doesn't have default value
int sum(int x, int y, int z=0, int w)

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Recommended Posts:

Writing code in comment? Please use, generate link and share the link here.