可能的重复:
在 C++ 的条件或控制语句中声明和初始化变量 https://stackoverflow.com/questions/1516919/declaring-and-initializing-a-variable-in-a-conditional-or-control-statement-in-c
而不是这个...
int value = get_value();
if ( value > 100 )
{
// Do something with value.
}
...是否可以缩小范围value只到需要的地方:
if ( int value = get_value() > 100 )
{
// Obviously this doesn't work. get_value() > 100 returns true,
// which is implicitly converted to 1 and assigned to value.
}
如果您想要特定的值范围,您可以引入范围块。
#include <iostream>
int get_value() {
return 101;
}
int main() {
{
int value = get_value();
if(value > 100)
std::cout << "Hey!";
} //value out of scope
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)