在 C 中声明的、未初始化的变量会发生什么?它有价值吗? [英] What happens to a declared, uninitialized variable in C? Does it have a value?

查看:22
本文介绍了在 C 中声明的、未初始化的变量会发生什么?它有价值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果在 C 中我写:

int num;

在给num赋值之前,num的值是不确定的吗?

Before I assign anything to num, is the value of num indeterminate?

推荐答案

静态变量(文件作用域和函数静态)被初始化为零:

Static variables (file scope and function static) are initialized to zero:

int x; // zero
int y = 0; // also zero

void foo() {
    static int x; // also zero
}

非静态变量(局部变量)不确定.在赋值之前读取它们会导致未定义行为.

Non-static variables (local variables) are indeterminate. Reading them prior to assigning a value results in undefined behavior.

void foo() {
    int x;
    printf("%d", x); // the compiler is free to crash here
}

在实践中,它们最初往往只有一些无意义的值——一些编译器甚至可能会放入特定的、固定的值,以便在调试器中查看时显而易见——但严格来说,编译器可以自由地做任何事情崩溃到通过你的鼻腔召唤恶魔.

In practice, they tend to just have some nonsensical value in there initially - some compilers may even put in specific, fixed values to make it obvious when looking in a debugger - but strictly speaking, the compiler is free to do anything from crashing to summoning demons through your nasal passages.

至于为什么它是未定义的行为而不是简单的未定义/任意值",有许多 CPU 架构在它们的各种类型的表示中具有额外的标志位.一个现代的例子是 安腾,它有一个不是一个东西"其寄存器中的位;当然,C 标准起草者正在考虑一些较旧的架构.

As for why it's undefined behavior instead of simply "undefined/arbitrary value", there are a number of CPU architectures that have additional flag bits in their representation for various types. A modern example would be the Itanium, which has a "Not a Thing" bit in its registers; of course, the C standard drafters were considering some older architectures.

尝试使用设置了这些标志位的值可能会导致 CPU 在确实不应该失败的操作中发生异常(例如,整数加法或分配给另一个变量).如果你让一个变量未初始化,编译器可能会在设置了这些标志位的情况下捡起一些随机垃圾 - 这意味着接触未初始化的变量可能是致命的.

Attempting to work with a value with these flag bits set can result in a CPU exception in an operation that really shouldn't fail (eg, integer addition, or assigning to another variable). And if you go and leave a variable uninitialized, the compiler might pick up some random garbage with these flag bits set - meaning touching that uninitialized variable may be deadly.

这篇关于在 C 中声明的、未初始化的变量会发生什么?它有价值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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