简体   繁体   English

只初始化一次非 static 局部变量

[英]initialize only once non static local variable

void foo() {    
    static int x{0};
    int y{0}; // this one
    // dosomething like ++y
    foo();    
}

Is it possible to have variable 'y' initialized only once(when foo called first time, not in each call) but separate independent local copy of it in each stack frame.是否可以只初始化一次变量“y”(当第一次调用 foo 时,而不是在每次调用中),但在每个堆栈帧中单独的独立本地副本。 while possible to change it in each stack frame(like ++y).虽然可以在每个堆栈帧中更改它(如 ++y)。

initialize only once non static local variable只初始化一次非 static 局部变量

By calling the function only once.只需拨打一次 function。

If you want a local variable initialised once in a function called multiple times, then that's what static local variables are for.如果你想在多次调用的 function 中初始化一次局部变量,那么这就是 static 局部变量的用途。

PS Your example function has infinite recursion. PS 你的例子 function 有无限递归。 It will overflow the stack.它会溢出堆栈。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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