为什么返回未初始化的值被认为是未定义的行为? [英] Why is returning a non-initialized value considered undefined behavior?

查看:311
本文介绍了为什么返回未初始化的值被认为是未定义的行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读时,我看到了一个我不知道的UB不明白,希望你能澄清

While reading this I saw a UB that I don't understand, hoping you can clarify

size_t f(int x)
{
    size_t a;
    if(x) // either x nonzero or UB
        a = 42;
    return a; 
}

我想UB是由于a没有初始化值引起的,但这不是它的已定义行为吗?这意味着f(0)将返回变量a所保存的值,无论它是什么(我认为这类似于rand()).我们是否必须知道代码片段为使代码具有明确定义的行为而返回的值是什么?

I guess the UB is due to a not having an initialized value, but isn't that it's defined behavior? Meaning, f(0) will return the value held by variable a, whatever it is (I consider this to be something like rand()). Must we know what value the code snippet returns for the code to have a well-defined-behavior?

推荐答案

意思是,f(0)将返回变量a所保存的值,无论它是什么...

好吧,在您的情况下,

  • a是自动局部变量
  • 它可以具有陷阱表示
  • 它没有地址.
  • a is automatic local variable
  • it can have trap representation
  • it does not have its address taken.

是的,根据定义,这会导致未定义的行为.

So, yes, this, by definition causes undefined behavior.

引用C11,第6.3.2.1章

Quoting C11, chapter §6.3.2.1

[...]如果 左值表示一个自动存储持续时间的对象,该对象本来可以 用寄存器存储类声明(从未使用其地址),然后声明该对象 未初始化(未使用初始化程序声明,并且尚未对其进行赋值 使用之前执行),则行为是不确定的.

[...] If the lvalue designates an object of automatic storage duration that could have been declared with the register storage class (never had its address taken), and that object is uninitialized (not declared with an initializer and no assignment to it has been performed prior to use), the behavior is undefined.


  • 与为什么未定义行为未定义"有关,请参见这篇文章.
  • 关于陷阱表示和未定义的行为,有一个很好的答案,检查一下.
  • 最后,在 UB和不确定值的使用之间可以有一个很好的联系.

    • Related to "why undefined behaviour is undefined", see this post.
    • There's a very nice answer related to trap representation and undefined behaviour, check it out.
    • Finally, a fine lining between UB and usage of indeterminate values.
    • 这篇关于为什么返回未初始化的值被认为是未定义的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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