What are Default Arguments?
A default argument is a value given in the declaration that the compiler automatically inserts if you don’t provide a value in the function call. Only trailing arguments may be defaulted. You can’t have a default argument followed by a non-default argument. Once you start using default arguments in a particular function call, all the subsequent arguments in that function’s argument list must be defaulted. Default arguments are only placed in the declaration of a function.
This example prints 2 to standard output, because the a referred to in the declaration of g() is the one at file scope, which has the value 2 when g() is called.
- include <iostream>
using namespace std;
int a = 1;
int f(int a) { return a; }
int g(int x = f(a)) { return x; }
int h() {
a = 2;
{
int a = 3;
return g();
}
}
int main() {
cout << h() << endl;
}
C++ FAQ Home