gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:09:10 29 4
gpt4 key购买 nike

在 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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com