c++ - 开关盒 : declaration-with-initialization & declaration-and-then-assignment

标签 c++ switch-statement jump-table

在 switch-case 语句中,declaration-with-initialization 是无效的,但允许 declaration-and-then-assignment。如以下代码片段所示。

从编译器端看,这两种类型的初始化有什么区别?以及为什么第一种初始化无效而第二种初始化有效。

switch(val)  
{  
case 0:  
  int newVal = 42;  //Invalid
  break;
case 1:  
  int newVal2;      //Valid
  newVal2 = 42;  
  break;
case 2:
  break;
}

最佳答案

实际上,规则是您不能跳入经过具有初始化的声明(或经过非 POD 类型变量的声明)的 block 。 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 部分)。该程序格式错误,因为如果 val12,您将在初始化后跳转到 switch block 。

int newVal2;也是一个声明;因为 int 是一个 POD 类型并且声明没有初始化器,你可以跳过这个声明。

关于c++ - 开关盒 : declaration-with-initialization & declaration-and-then-assignment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3757445/

相关文章:

添加输出文件后 C++ 代码无法正确编译

c - 使用 C30 和 MPLAB X 的 switch 语句的奇怪行为

c - 使用嵌套开关 fork 两个 child

c++ - c 切换和跳转表

c++ - 由 adobe 完成的用于对图像进行采样的 HSV 值范围

c++ - SSE-C++ 内存溢出

c++ - Boost.Preprocessor 使用宏而不是简单定义的基本原理?

java - 反编译后$SwitchMap$错误

java - Java 中有类似分支/跳转表的东西吗?