在不指定值的情况下打印变量

Naz*_*lam -1 c++ c++11

在C++中,如果我打印一个尚未赋值的变量会怎样?以下两个代码给出了两个不同的结果.此外,第一个在每个编辑中给出不同的结果,第二个每次打印0.为什么?

int main() {
    int x = 1;
    int y;   // No value has been assigned
    if (x) {
        cout << y;    // without using endl
        // prints different value each time
    }
}
Run Code Online (Sandbox Code Playgroud)

int main() {
    int x = 1;
    int y;   // y is not initialized
    if (x) {
        cout << y << endl;    // using endl
        // prints 0
    }
}
Run Code Online (Sandbox Code Playgroud)

Ker*_* SB 5

读取未初始化的值(更具体地说,对不确定的值执行左值到右值的转换,这是由于未初始化对象而产生的)具有未定义的行为 ; 换句话说,这两个程序都是错误的.