I learned that auto-variables aren’t initialized to zero. So the following code will behave correctly and prints random numbers on the screen:
#include <iostream>
using std::cout;
using std::endl;
void doSomething()
{
int i;
cout << i << endl;
}
int main()
{
doSomething();
}
But why won’t this snipped behave in the same way ?
#include <iostream>
using std::cout;
using std::endl;
void doSomething()
{
int i;
cout << i << endl;
}
int main()
{
int j;
cout << j << endl;
doSomething();
}
This snippet shows:
0
0
Does anyone know why “j” and “i” were suddenly initialized to zero here?
Using an uninitialized variable is undefined behaviour. It’s likely you wouldn’t get the same behaviour on another compiler. The only ‘why’ is to be found inside the source code to your specific C++ compiler.