发生在C中声明,未初始化的变量是什么?它有一个价值? [英] What happens to a declared, uninitialized variable in C? Does it have a value?
问题描述
如果用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.
至于为什么它是不确定的行为,而不是简单的未定义/任意值,也有一些有额外的标志位在其再presentation各类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屋!