If I don't assign a value to a variable when I declare it, does it default to zero or just whatever was previously in the memory?
e.g.
float x;
If I don't assign a value to a variable when I declare it, does it default to zero or just whatever was previously in the memory?
e.g.
float x;
It depends. If this is a local variable (an object with automatic storage duration) it will be uninitialized, if it is a global variable (an object with static storage duration) it will be zero initialized. Check also this answer.
C++ does not instantiate variables. The value of x is whatever happened to be in the memory at the time. Never assume anything about its initial value.
It depends on the lifetime of the variable. Variables with static lifetime are always zero-initialized before program start-up: zero-initialization for basic types,
enum
s and pointers is the same as if you'd assigned0
, appropriately converted to the type, to it. This occurs even if the variable has a constructor, before the constructor is called.It can be compiler specific but generally release builds don't initialise variables to any particular value, so you get whatever is left in memory. Certain magic numbers are used in debug builds by some compilers to mark specific areas of memory however.
This depends on where you declare it. Variables in the global scope are initialized with 0, and stack-variables are undefined.
Using the value of any variable prior to initialization (note that static-storage-duration objects are always initialized, so this only applies to automatic storage duration) results in undefined behavior. This is very different from containing 0 as the initial value or containing a random value. UB means it's possible that anything could happen. On implementations with trap bits it might crash your program or generate a signal. It's also possible that multiple reads result in different unpredictable values, among any other imaginable (or unimaginable) behavior. Simply do not use the value of uninitialized variables.
Note: The following was edited based on comments:
Note that code like this is invalid unless you can assure that the type
foo_t
does not have padding bits:Even though the intent is that the "random value" initially in
x
gets discarded before the loop ends, the program may invoke UB as soon as it accessesx
to perform the operationx<<1
on the first iteration, and thus the entire program output is invalidated.