gpt4 book ai didi

C++11:在 switch 语句中声明变量

转载 作者:搜寻专家 更新时间:2023-10-31 00:35:41 24 4
gpt4 key购买 nike

我知道 C++03 不允许在不使用的情况下在 switch block 中定义变量大括号。

const int i = ...
switch (i) { case 0: int j = 0; break; } // 1. error here
switch (i) { case 0: { int j = 0; } break; } // 2. ok

新的 C++11 标准是什么?它允许第一种形式吗?我也可以这样写吗:

switch (i) 
{
case 0: int j = 0; break;
case 1: int j = 0; break;
case 2: int j = 0; break;
}

最佳答案

case 语句没有(在 C++03 中)并且仍然没有(在 C++11 中)引入作用域。

标准在 [stmt.switch] (6.4.2/6) 中说:

case and default labels in themselves do not alter the flow of control, which continues unimpeded across such labels.

因此允许像这样“通过”case 语句:

int x, a = 1;
switch(a) {
case 1:
x = 5;
// no break here!
case 10:
x *= 4; // x is now 20.
}

例如,如果您在第一个 case 语句下面引入一个变量声明,则当跳转到第二个 case 语句时可以跳过它。

然而,您可以在 switch block 的开头声明一个局部变量:

switch (i) 
{
int j;
case 0: j = 0; break;
case 1: j = 0; break;
case 2: j = 0; break;
}

switch 实际上更像是一个跳转表,而不是一系列的 if/else if 语句。

关于C++11:在 switch 语句中声明变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23371952/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com