Search code examples
c++undefined-behaviorvariable-declaration

C++ declaring multiple integers prints different values


I am trying to learn c++ and I came across a very annoying inconsistency:

#include <iostream>
using namespace std;

int main (){
    int var1,var2,var3,var4,var5,var6,var7;

    cout << var1 << endl;
    cout << var2 << endl;
    cout << var3 << endl;
    cout << var4 << endl;
    cout << var5 << endl;
    cout << var6 << endl;
    cout << var7 << endl;

    return 0;
}

It returns the following:

0
4196128
0
570985680
32767
0
0

Why am I getting different values for these unset values? Shouldn't I get either 0 for each variable? What does the output that I am getting represent?


Solution

  • Uninitialized local variables will have indeterminate values, which will seem random. Reading their indeterminate value leads to undefined behavior.