gpt4 book ai didi

c++ - 跳过变量初始化格式不正确还是会导致不确定的行为?

转载 作者:行者123 更新时间:2023-12-01 09:06:14 25 4
gpt4 key购买 nike

考虑以下代码:

void foo()
{
goto bar;
int x = 0;
bar: ;
}

GCC和Clang reject it,因为跳转到 bar:会绕过变量初始化。 MSVC完全不提示(在 x引起警告之后使用 bar:除外)。

我们可以使用 switch做类似的事情:
void foo()
{
switch (0)
{
int x = 0;
case 0: ;
}
}

现在,所有三个编译器 emit errors

这些代码片段格式不正确吗?还是引起UB?

我曾经以为两者都是不正确的形式,但是我找不到标准的启示部分。 [stmt.goto]对此没有说什么, [stmt.select]也没有说。

最佳答案

初始化不为空时,它的格式不正确。

[stmt.dcl]

3 It is possible to transfer into a block, but not in a way that bypasses declarations with initialization (including ones in conditions and init-statements). A program that jumps from a point where a variable with automatic storage duration is not in scope to a point where it is in scope is ill-formed unless the variable has vacuous initialization ([basic.life]). In such a case, the variables with vacuous initialization are constructed in the order of their declaration.



初始化程序使初始化成为非空的。相比之下,这
void foo()
{
goto bar;
int x; // no initializer
bar: ;
}

格式正确。尽管有关使用带有不确定值的 x的通常警告会适用。

关于c++ - 跳过变量初始化格式不正确还是会导致不确定的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59931168/

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