Suppose I declare a variable x
and leave it uninitialized. I go on to print its value. I see some junk.
Where does it come from? Also why is it not used to generate random numbers? I mean instead of using a pseudo random generator.
Initializing a variable means specifying an initial value to assign to it (i.e., before it is used at all). Notice that a variable that is not initialized does not have a defined value, hence it cannot be used until it is assigned such a value.
In computing, an uninitialized variable is a variable that is declared but is not set to a definite known value before it is used. It will have some value, but not a predictable one. As such, it is a programming error and a common source of bugs in software.
An uninitialized variable has an undefined value, often corresponding to the data that was already in the particular memory location that the variable is using. This can lead to errors that are very hard to detect since the variable's value is effectively random, different values cause different errors or none at all.
So using an uninitialized variable will result in undefined behavior. Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output of a program that has undefined behavior.
The 'random' value is simply what's left in memory at that location. Memory usually isn't erased/zeroed when it's freed so whatever was there will linger until it's overwritten.
The junk may come from two places:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With