Default Parameters in C++ Functions

This post originated on Google+, where a friend of mine reported about default parameters being evaluated in the scope of the caller. This lead me to study the standard (that can be downloaded here). The result of my brief look into the standard:

Default parameters can be defined differently in different scopes like:

void f (int, int);
void f (int, int = 7); 
void h() {
void f(int = 1, int = 6);
  f(); // calls f(1,6);
}

In other scopes you can set other default values. That is probably the reason why no overloads are created when defining default arguments.

And the next clause is also quite interesting:

int a = 1;
int f();
int g(int = f(a));

void h() {
  a = 2;
  g(); // calls g(f(::a))
}

This explains further more, why no overloads are created...

The actual description of the behavior is in §1.9.12 of the standard in a "Note":
"[Note: The evaluation of a full-expression can include the evaluation of subexpressions that are not lexically part of the full-expression. For example, subexpressions involved in evaluating default arguments (8.3.6 ) are considered to be created in the expression that calls the function, not the expression that defines the default argument. — end note]"

Leave a Reply

Your email address will not be published. Required fields are marked *