在 switch-case 语句中声明与初始化无效但是声明然后赋值被允许。如下面的代码片段所示。
从编译器方面来看,这两种类型的初始化有什么区别?为什么第一种类型的初始化无效而第二种类型的初始化有效。
switch(val)
{
case 0:
int newVal = 42; //Invalid
break;
case 1:
int newVal2; //Valid
newVal2 = 42;
break;
case 2:
break;
}
实际上,规则是您不能跳入经过具有初始化的声明(或经过非 POD 类型变量的声明)的块。 C++ 标准规定 (C++03 §6.7):
It is possible to transfer into a block, but not in a way that bypasses declarations with initialization. A program that jumps(77) from a point where a local variable with automatic storage duration is not in scope to a point where it is in scope is ill-formed unless the variable has POD type (3.9) and is declared without an initializer (8.5).
(*) The transfer from the condition of a switch
statement to a case
label is considered a jump in this respect.
int newVal = 42;
是一个具有初始值设定项的声明(= 42
部分)。该程序格式错误,因为如果val
is 1
or 2
,您将跳入初始化后的 switch 块。
int newVal2;
也是一个声明;因为int
是 POD 类型并且声明没有初始化程序,您可以跳过此声明。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)