In most languages I know, scalar-type variables are zero-initialized by default, if they were not initialized in the code. Why doesn't this happen in c/c++? The only reason I could think of is performance, but
Wouldn't it be easier to explicitly tell the compiler somehow not to zero-initialize a variable, if this might be a performance issue?
An finally my question: Is there a gcc option to tell the compiler to zero-init by default?
In C programming language, the variables should be declared before a value is assigned to it. In an array, if fewer elements are used than the specified size of the array, then the remaining elements will be set by default to 0. Let us see another example to illustrate this.
Zero is initialized for every named variable with static or thread-local storage duration that is not subject to constant initialization (since C++14), before any other initialization.
Unlike some programming languages, C/C++ does not initialize most variables to a given value (such as zero) automatically. Thus when a variable is assigned a memory location by the compiler, the default value of that variable is whatever (garbage) value happens to already be in that memory location!
INTRODUCTION: 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.
One of the founding principals of c++ is to not force developers to pay for what they don't use. If you write something like int x; x = 1;
then you shouldn't have to pay for the zero initialization of x
, even if that cost happens to be very tiny.
Edit : Regarding your other two points
is it preferable to have undefined behavior?
Undefined behavior is not necessarily a bad thing to have in the language (you can argue both ways). It's definitely a bad thing if you write code that causes it. Notably it gives more freedom to implementers and enables important optimizations.
if I want to avoid undefined behavior, I have to initialize it anyway, so what did I win?
It's not undefined behavior to have an uninitialized variable. It's undefined behavior to try to read from one.
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