当我在 C++ 中打印未初始化的变量时会发生什么?
为什么会打印 32767
(或其他一些随机数)?什么是 std::cout 打印?为什么它不是NULL
(或0
)?
int main()
{
int a;
std::cout << a;
}
Why does this print 32767
(or some other random number)? What is std::cout
printing? Why is it not NULL
(or 0
)?
int main()
{
int a;
std::cout << a;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是因为在 C++ 中具有自动存储期限的变量不会自动初始化为零。在 C++ 中,您不需要为不需要的东西付费,并且自动初始化变量需要时间(将内存位置设置为零最终会减少机器指令,然后将其转换为控制物理位的电信号)。
该变量被保留在一个内存位置,而该内存位置恰好有一些垃圾。这些垃圾正在被
cout
打印出来。正如@dwcanillas 所指出的,这是未定义的行为。相关:C 中声明的未初始化变量会发生什么情况?它有值吗?
来自 C++ 标准(强调我的):
8.5 初始化器 [dcl.init]
That is because variables with automatic storage duration are not automatically initialized to zero in C++. In C++, you don't pay for what you don't need, and automatically initializing a variable takes time (setting to zero a memory location ultimately reduces to machine intruction(s) which are then translated to electrical signals that control the physical bits).
The variable is being reserved a memory location, and it happens that some junk is at that memory location. That junk is being printed out by
cout
.As pointed out by @dwcanillas, it is undefined behaviour. Related: What happens to a declared, uninitialized variable in C? Does it have a value?
From the C++ standard (emphasize mine):
8.5 Initializers [dcl.init]
这是未定义的行为。您正在打印占用
a
内存的任何内容,在本例中恰好是32767
。It's undefined behavior. You are printing whatever occupies the memory of
a
, which in this case happens to be32767
.C++14 (N3936) [dcl.init]/12 涵盖了该行为:
并且您的代码不包含在任何涵盖少数情况的“以下情况” 中允许传播
unsigned char
不确定值的情况。The behaviour is covered by C++14 (N3936) [dcl.init]/12:
and your code is not covered by any of the "following cases" which cover a few situations in which
unsigned char
indeterminate values are allowed to propagate.因为“a”不是全局/静态的。它是一个自动变量,在运行时进行初始化。如果它是全局的,则在编译时就会初始化为零。即:
• 静态变量在编译时初始化,因为它们的地址是已知且固定的。将它们初始化为 0 不会产生运行时成本。
• 自动变量对于不同的调用可以有不同的地址,并且必须在每次调用函数时在运行时初始化,从而产生可能不需要的运行时成本。如果您确实需要初始化,请请求它。
Because "a" is not global/static. Its an automatic variable for which initialization happens at run time. If it was global, initialization to zero would have happened at compile time. i.e
• static variables are initialized at compile-time, since their address is known and fixed. Initializing them to 0 does not incur a runtime cost.
• automatic variables can have different addresses for different calls and would have to be initialized at runtime each time the function is called, incurring a runtime cost that may not be needed. If you do need that initialization, then request it.