csguy
csguy

Reputation: 1474

What happens when you initialize a parameter? C++

void foo (int i , int k = 7) {
    cout << k;
}

int main(){
    foo(1, 2);    
}

k will output 2. My question is, in what order does foo initialize the parameter and acquire the argument? What is the process foo goes through to get 2. Thank you

Upvotes: 2

Views: 305

Answers (3)

Kevin Cyu
Kevin Cyu

Reputation: 24

This is called function initializer.

If you don't assign the second parameter as foo(1,2) , it'll output "7" on the screen (when you use foo(1) ).

Upvotes: 0

Miles Budnek
Miles Budnek

Reputation: 30494

Your example is no different than if you had declared foo without the default parameter.

Default parameters are handled by the compiler. When the compiler encounters a call to foo with only one parameter, it will add the second parameter for you.

For example:

foo(3);

will get transformed by the compiler to

foo(3, 7);

That's all.

Upvotes: 1

A.S.H
A.S.H

Reputation: 29332

 void foo (int i , int k = 7);

This prototype means that if you call foo with only the first param the second is implicitly set to 7.

    foo(1, 2);  // i=1, k=2
    foo(5);  // <==> foo(5, 7)   i=1, k=7

This mechanism is resolved at compile time, by the compiler. Whenever foo is called with the param k missing, the compiler automatically inserts it with the value 7 (i.e. foo(5)). If it is not missing, the actual parameter is taken (i.e. foo(1, 2)).

Upvotes: 6

Related Questions