gpt4 book ai didi

c - 为什么返回一个未初始化的值被认为是未定义的行为?

转载 作者:太空狗 更新时间:2023-10-29 15:54:14 24 4
gpt4 key购买 nike

阅读时this看到一个UB,不太懂,希望大家指点一下

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() ).我们必须知道代码片段返回什么值才能使代码具有明确定义的行为吗?

最佳答案

Meaning, f(0) will return the value held by variable a, whatever it is...

嗯,在你的情况下,

所以,是的,根据定义,这会导致 undefined behavior .

引用 C11,章节 §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.


关于c - 为什么返回一个未初始化的值被认为是未定义的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43980679/

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