如果我在 C 中写:
int num;
在我分配任何东西之前num
,是值num
不定?
静态变量(文件作用域和函数静态)初始化为零:
int x; // zero
int y = 0; // also zero
void foo() {
static int x; // also zero
}
非静态变量(局部变量)是不定。在赋值之前读取它们会导致未定义的行为.
void foo() {
int x;
printf("%d", x); // the compiler is free to crash here
}
实际上,它们最初往往只是有一些无意义的值 - 一些编译器甚至可能会放入特定的固定值,以便在调试器中查看时变得明显 - 但严格来说,编译器可以自由地执行从崩溃到召唤的任何操作恶魔通过你的鼻道 http://catb.org/jargon/html/N/nasal-demons.html.
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 http://blogs.msdn.com/oldnewthing/archive/2004/01/19/60162.aspx the Itanium, which has a "Not a Thing" bit in its registers https://web.archive.org/web/20190127204712/https://blogs.msdn.microsoft.com/oldnewthing/20040119-00/?p=41003; of course, the C standard drafters were considering some older architectures.
尝试使用设置了这些标志位的值可能会导致 CPU 操作异常really不应失败(例如,整数加法或分配给另一个变量)。如果你留下一个未初始化的变量,编译器可能会在设置了这些标志位的情况下拾取一些随机垃圾 - 这意味着触摸该未初始化的变量可能是致命的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)