C++中,带有和不带有初始化器的if和switch语句的辨析与使用

    科技2022-09-06  127

    带有初始化器的if和switch语句

    if and swtich Statement with an Initializer

    1. 带/不带初始化器的if语句

    不带初始化器的if语句 int foo(int arg) { // do something return (arg); } int main() { auto x = foo(42); if (x > 40) { // do something with x } else { // do something with x } // auto x = 3; } 带有初始化器的if语句 int foo(int arg) { // do something return (arg); } int main() { // auto x = foo(42); if (auto x = foo(42); x > 40) { // do something with x } else { // do something with x } auto x = 3; // 名字 x 可重用 } 区别:

    带有初始化器的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: // do something default: std::cout << "i = " << i << std::endl; break; }

    4. 注意

    if语句中的初始化器只能使用新变量,不能使用之前已经出现过的变量。

    Processed: 0.009, SQL: 9