c - 对未初始化变量有任何保证吗?

标签 c undefined-behavior

有许多说法称,任何未初始化变量的使用都会调用 undefined behavior (UB) .
仔细阅读文档,我无法验证该声明,因此我需要一个令人信服的论据来澄清 C 和 C++ 的这一点。
我期望两者具有相同的语义,但我准备对细微或不那么细微的差异感到惊讶。

一些使用未初始化变量的示例。请根据需要添加其他内容,以解释它们未涵盖的任何极端情况。

void test1() {
    int x;
    printf("%d", x);
}

void test2() {
    int x;
    for(int i = 0; i < CHAR_BIT * sizeof x)
        x = x << 1;
    printf("%d", x);
}

void test3() {
    unsigned x;
    printf("%u", x); /* was format "%d" */
}

void test4() {
    unsigned x;
    for(int i = 0; i < CHAR_BIT * sizeof x)
        x = x << 1;
    printf("%u", x); /* was format "%d" */
}

最佳答案

在 C 语言中,所有这些都是未定义的行为,但其原因可能不会直接浮现在脑海中。如果访问具有不确定值的对象,则具有未定义的行为 “无内存”即 6.3.2.1 p2

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.

否则,如果地址被获取,则在这种情况下对不确定具体含义的解释并不一致。有些人期望这样的值在第一次读取后就被修复,其他人则谈到诸如“woobly”(或类似)的值,这些值在每次访问时都可能不同。

总而言之,不要这样做。 (但你可能已经知道了。)

(并且不谈论使用“%d”表示无符号的错误。)

关于c - 对未初始化变量有任何保证吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22839466/

相关文章:

c - "Illegal hardware instruction"来自非常简单的代码

在 C 中将指针转换回数组

代码不显示返回值

c - C中的二进制文件读取操作?

C++ 异常、未定义行为和 noexcept

我们可以通过指针来改变const定义的对象的值吗?

c++ - 为什么未诊断出在 constexpr 上下文中使用保留的标识符名称?

c - C 中 Socket 中的大文件传输错误

c - while 循环中的递增和递减

c - 在 C 中没有参数的 printf() 可以正常编译。如何?