Switch-Case:声明与初始化 &声明然后赋值 [英] Switch-Case: declaration-with-initialization & declaration-and-then-assignment

查看:22
本文介绍了Switch-Case:声明与初始化 &声明然后赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

可以转移到块中,但不能通过初始化绕过声明.除非变量具有 POD 类型 (3.9),否则从具有自动存储持续时间的局部变量不在范围内的点跳转到其在范围内的点的程序(77) 是格式错误的并且在没有初始化程序的情况下声明 (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).

(*) 从 switch 语句的条件到 case 标签的转移在这方面被认为是一个跳转.

(*) 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 块.

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.

这篇关于Switch-Case:声明与初始化 &声明然后赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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