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

编程入门 行业动态 更新时间:2024-10-25 07:20:17
本文介绍了跳过变量初始化格式不正确还是会导致未定义的行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

考虑以下代码:

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

GCC和Clang 拒绝它,因为跳转到bar:会绕过变量初始化. MSVC根本不抱怨(除非在bar:引起警告后使用x).

GCC and Clang reject it, because the jump to bar: bypasses variable initialization. MSVC doesn't complain at all (except using x after bar: causes a warning).

我们可以使用switch做类似的事情:

We can do a similar thing with a switch:

void foo() { switch (0) { int x = 0; case 0: ; } }

现在所有三个编译器发出错误.

这些代码片段格式不正确吗?还是会导致UB?

Are those snippets ill-formed? Or do they cause UB?

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

I used to think that both were ill-formed, but I can't find the revelant parts of the standard. [stmt.goto] doesn't say anything about this, and neither does [stmt.select].

推荐答案

初始化非空时,它的格式不正确.

It's ill-formed when the initialization is non-vacuous.

[stmt.dcl]

3 可以转移到块中,但不以这种方式 绕过初始化声明(包括中的声明) 条件和初始化声明).从一个点跳下来的程序 具有自动存储期限的变量不在范围内 除非变量具有 空泡初始化([basic.life]).在这种情况下,变量 空虚初始化按其顺序构造 声明.

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.

初始化程序使初始化不为空.相比之下,

The initializer makes the initialization non-vacuous. To contrast, this

void foo() { goto bar; int x; // no initializer bar: ; }

将格式正确.尽管通常会出现关于将x使用不确定值的警告.

would be well-formed. Though the usual caveats about using x with an indeterminate value would apply.

更多推荐

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

本文发布于:2023-11-10 06:11:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1574569.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:初始化   不正确   变量   跳过   未定义

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!