I recently found out that in C++, declaring int's outside of a function will initialize them to 0
, but inside a function the behavior is undefined, and will return a nonsense value or potentially crash the compiler. However I found that if I declare an int (let's call it j
) in a function but then print it by writing cout << j;
, it will print 0
and from there on within the function it will equal 0
and act as such.
Firstly, why does printing do this? Why does this cause an undeclared int inside a function to stop acting like a nonsense value and start acting like it was implicitly initialized to 0
, as it does outside functions?
Secondly, why does C++ work this way to begin with? Which genius decided that uninitialized int's should act in a well defined manner outside functions, but not within them? Wouldn't this be trivial to specify and implement with a compiler? Why on God's Green Earth is this how it works?