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

2021-01-30  本文已影响0人  陈成_Adam

不带初始化器的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块,则可更好地优化代码)

上一篇下一篇

猜你喜欢

热点阅读