为什么intb;在外壳/终端中有16个值?

#include <iostream>

using namespace std;

int main()
{
    int a;
    int b;
    
    cout<<a<<endl;
    cout<<b;

}

为什么我编译这个时 b 有 16 个值?我不明白为什么 b 有 16 而不是 0。Int 没有 0 作为默认值?

回答

绝对不。C++ 不会初始化变量,除非你要求它。(例如,将变量设置为 0 至少是一条指令:通常是reg XOR reg。这可能很浪费。)读取未初始化的行为int是未定义的。

(请注意,您可以使用未初始化的变量做一些事情,例如设置一个指针或对一个的引用、计算sizeof(a)和使用decltype(a)。但将其按值传递给函数是未定义的行为。即使是专业程序员也经常会遇到这种情况。)

  • Again, absolutely not. Only if you need to read the value before you write something sensible to it.
  • `a += 1` is a read of an uninitialised `a`. You are incrementing the value.
  • @lolorek: `a + 10` is an uninitialised read of `a`. Can you not see that? Did you mean `a = 10`?

以上是为什么intb;在外壳/终端中有16个值?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>