开关情况:声明与初始化&声明和分配 [英] Switch-Case: declaration-with-initialization & declaration-and-then-assignment

查看:164
本文介绍了开关情况:声明与初始化&声明和分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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):


可以传入一个块,使用初始化绕过声明。一个程序跳过(77)从自动存储持续时间的局部变量不在范围内的点到其范围内的点,除非变量具有POD类型(3.9)并且没有初始化程序(8.5)。

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).

(*)从开关

int newVal = 42; 是一个具有初始化程序( = 42 )的声明。程序是不成形的,因为如果 val 1 2

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.

这篇关于开关情况:声明与初始化&声明和分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆