Switch-Case:带有初始化的声明&声明然后赋值
在 switch-case 语句中,带初始化的声明无效,但允许声明然后赋值。如下面的代码片段所示。
从编译器方面来看,这两种类型的初始化有什么区别?为什么第一种类型的初始化无效而第二种类型的初始化有效。
switch(val)
{
case 0:
int newVal = 42; //Invalid
break;
case 1:
int newVal2; //Valid
newVal2 = 42;
break;
case 2:
break;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
实际上,规则是您不能跳入经过具有初始化的声明(或经过非 POD 类型变量的声明)的块。 C++ 标准规定 (C++03 §6.7):
int newVal = 42;
是一个具有初始值设定项的声明(= 42
部分)。该程序格式不正确,因为如果val
为1
或2
,您将跳到初始化之后的 switch 块。int newVal2;
也是一个声明;因为int
是 POD 类型并且该声明没有初始值设定项,因此您可以跳过该声明。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):
int newVal = 42;
is a declaration that has an initializer (the= 42
part). The program is ill-formed because ifval
is1
or2
, you'll jump into the switch block past the initialization.int newVal2;
is also a declaration; becauseint
is a POD type and the declaration has no initializer, you can jump past this declaration.事实上,两者都不是合法的 C++。你不能在 switch case 中声明一个变量,除非它是有作用域的:
你的编译器允许 case 1 的事实是你的编译器的一个缺陷,或者可能是一个扩展。至少,按照标准。
In fact, neither are legal C++. You cannot declare a variable in a switch case unless it is scoped:
The fact that your compiler permits case 1 is a defect of your compiler, or possibly an extension. At least, according to the standard.