问题描述
在switch-case语句声明与初始化无效,但声明和然后赋值是允许的。如下面的代码片段所示。
In the switch-case statements declaration-with-initialization is invalid but declaration-and-then-assignment is allowed. As shown in the following code snippet.
这两种类型的初始化从编译器方面有什么区别?为什么第一种类型的初始化无效,第二种类型是有效的。
What is difference between these two type of initializations from the compiler side? And why is the first type of initialization invalid and second type a valid one.
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):
Effectively, the rule is that you can't jump into a block past a declaration that has an initialization (or past the declaration of a non-POD type variable). The C++ standard says (C++03 §6.7):
(*)从开关$ c $
int newVal = 42;
是一个具有初始化程序( = 42
)的声明。程序是不成形的,因为如果 val
是 1
或 2 $ c $
int newVal = 42;
is a declaration that has an initializer (the = 42
part). The program is ill-formed because if val
is 1
or 2
, you'll jump into the switch block past the initialization.
int newVal2;
也是一个声明;因为 int
是一个POD类型,声明没有初始化,你可以跳过这个声明。
int newVal2;
is also a declaration; because int
is a POD type and the declaration has no initializer, you can jump past this declaration.
这篇关于开关情况:声明与初始化&声明和分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!