When you initialize a non-static(local) variable and use/read/print it before assigning a variable to it, the action is undefined behavior
.
When you encounter undefined behavior
:
- You cannot assume that there's any value in that memory space to begin with
- You cannot assume that the value won't change throughout the code execution, therefore, it's not ideal to use it as an ID
- You cannot even assume that the program will run, or it will crash/freeze/etc... as everything action from that point on is
undefined
Theoretically, an undefined behavior
permits anything to happen (obviously in reality there's many restrictions to try and keep it from doing everything and probably sending everyone your pictures, corrupt all your files and frying your computer afterward).
For example, with this piece of code:
int num;
int a = num;
int b = num;
When you print it out, a
and b
is not guaranteed to have identical value, or the program will run at all. It's different with each systems/compilers.
As such, one must never rely on an undefined behavior
to act normally.
Quote from @AnT:
So in general, the popular answer that "it is initialized with
whatever garbage was in memory" is not even remotely correct.
Uninitialized variable's behavior is different from that of a variable
initialized with garbage.
However, never mistakes undefined
for inconsistency/randomness
. For a (pretty bad) real life example, a broken pipe may be unexpected behavior, but the stream of water that hits you isn't inconsistent or random (until the pipe is fixed, of course).
An example when undefined behavior isn't simply taking some garbage value and results in some bizarre stuff: https://devblogs.microsoft.com/oldnewthing/20140627-00/?p=633
Related :