switch-case 语句中的变量声明
Variable declaration in switch-case statements
switch
-case
语句中的变量声明问题在this SO post中讨论得很好,答案涵盖了大部分方面。但是我遇到了一个问题,因为我找不到充分的理由。有人可以解释一下这段代码有什么问题吗?
switch (var)
{
case 0:
int test;
test = 0; // no error
int test2 = 0; // ERROR: initialization of 'test2' is skipped by 'case' label
std::string str;
str = "test"; // ERROR: initialization of 'str' is skipped by 'case' label
break;
case 1:;
break;
}
我知道为什么第6行会出错。但是接下来的两行有什么问题呢?我认为这可能与原生类型和 class 类型的区别有关,但我不确定。
这不是 Why can't variables be declared in a switch statement? 的重复问题!因为我已经为原来的提供了 link。请阅读这两个问题并注意区别。 AFAIK,原始问题中未讨论问题。
It is possible to transfer into a block, but not in a way that bypasses declarations with initialization. A
program that jumps 90 from a point where a variable with automatic storage duration is not in scope to a
point where it is in scope is ill-formed unless the variable has scalar type, class type with a trivial default
constructor and a trivial destructor, a cv-qualified version of one of these types, or an array of one of the
preceding types and is declared without an initializer (8.5).
([stmt.dcl]/3)
直观的解释是,如果声明执行的初始化实际上是空操作,则您只能跳过该声明。如果提供了一个值,则不能跳过它。如果aclass的构造函数中有代码,则不能跳过。
switch
-case
语句中的变量声明问题在this SO post中讨论得很好,答案涵盖了大部分方面。但是我遇到了一个问题,因为我找不到充分的理由。有人可以解释一下这段代码有什么问题吗?
switch (var)
{
case 0:
int test;
test = 0; // no error
int test2 = 0; // ERROR: initialization of 'test2' is skipped by 'case' label
std::string str;
str = "test"; // ERROR: initialization of 'str' is skipped by 'case' label
break;
case 1:;
break;
}
我知道为什么第6行会出错。但是接下来的两行有什么问题呢?我认为这可能与原生类型和 class 类型的区别有关,但我不确定。
这不是 Why can't variables be declared in a switch statement? 的重复问题!因为我已经为原来的提供了 link。请阅读这两个问题并注意区别。 AFAIK,原始问题中未讨论问题。
It is possible to transfer into a block, but not in a way that bypasses declarations with initialization. A program that jumps 90 from a point where a variable with automatic storage duration is not in scope to a point where it is in scope is ill-formed unless the variable has scalar type, class type with a trivial default constructor and a trivial destructor, a cv-qualified version of one of these types, or an array of one of the preceding types and is declared without an initializer (8.5).
([stmt.dcl]/3)
直观的解释是,如果声明执行的初始化实际上是空操作,则您只能跳过该声明。如果提供了一个值,则不能跳过它。如果aclass的构造函数中有代码,则不能跳过。