What happens when you initialize a parameter? C++

浪子不回头ぞ 提交于 2019-12-12 19:25:54

问题


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


回答1:


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




回答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.




回答3:


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



来源:https://stackoverflow.com/questions/40954623/what-happens-when-you-initialize-a-parameter-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!