美文网首页
C++新特性之带有初始化器的if和switch语句

C++新特性之带有初始化器的if和switch语句

作者: 陈成_Adam | 来源:发表于2021-01-30 22:26 被阅读0次

    不带初始化器的if语句

    int foo(int arg) { // do something
      return (arg);
    }
    int main() {
      auto x = foo(42); // 本应限制于if块的变量,侵入了周边的作用域
      if (x > 40) {
        // do something with x
      } else {
        // do something with x
      }
      // auto x  = 3;
    }
    

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

    带有初始化器的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 可重用
    }
    

    带有初始化器的switch语句:

    switch (int i = rand() % 100; i) {
      case 1:
        // do something
      default:
        std::cout << "i = " << i << std::endl;
        break;
    }
    

    为何要使用带有初始化器的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块,则可更好地优化代码)

    相关文章

      网友评论

          本文标题:C++新特性之带有初始化器的if和switch语句

          本文链接:https://www.haomeiwen.com/subject/ouxltltx.html