简体   繁体   中英

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

 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 (ie foo(5) ). If it is not missing, the actual parameter is taken (ie foo(1, 2) ).

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.

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) ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM