带有初始化器的if和switch语句
if and swtich Statement with an Initializer
1. 带/不带初始化器的if语句
不带初始化器的if语句
int foo(int arg
) {
return (arg
);
}
int main() {
auto x
= foo(42);
if (x
> 40) {
}
else {
}
}
带有初始化器的if语句
int foo(int arg
) {
return (arg
);
}
int main() {
if (auto x
= foo(42); x
> 40) {
}
else {
}
auto x
= 3;
}
区别:
带有初始化器的if语句中的某个变量作用域比无初始化器的变量作用域小。
2. 为何要使用带有初始化器的if语句
The variable, which ought to be limited in if block, leaks into the surrounding scope (本应限制于if块的变量,侵入了周边的作用域)The compiler can better optimize the code if it knows explicitly the scope of the variable is only in one if block (若编译器确知变量作用域限于if块,则可更好地优化代码)
3. 带有初始化器的switch语句
语法: switch(initializer;variable)
switch (int i
= rand() % 100; i
) {
case 1:
default:
std
::cout
<< "i = " << i
<< std
::endl
;
break;
}
4. 注意
if语句中的初始化器只能使用新变量,不能使用之前已经出现过的变量。