In C language, is
int x, y, z = 0;
the same as this?
int x = 0;
int y = 0;
int z = 0;
Also, if I just say int a;
, it seems that the value of a
is zero even if it is uninitialized, but not undefined as described in What will be the value of uninitialized variable?
No the two are not equivalent.
int x, y, z = 0;
In this line x
and y
will have indeterminate value, while z
is initialized to zero.
You can however keep it in "one line" for the price of some verbosity:
int x = 0, y = x, z = y;
Now all three are initialized with the same value (the one you gave x
). To initialize one variable with another, all that is required is for the initializer to be previously defined. And it works even if it's on the same line. The above will also allow you to change the initial value for all variable quite easily.
Alternatively, if you find the previous style ugly, you can make it work in two lines:
int x, y, z;
x = y = z = 0;
But it's now assignment, and not initialization.
Also, if I just say
int a;
, it seems that the value ofa
is zero even if it is uninitialized, but not undefined as described in What will be the value of uninitialized variable?
"Indeterminate value" doesn't mean "not-zero". There is nothing about zero that makes it an invalid candidate for the variables initial value. Some "helpful" compilers zero initialize variables in debug builds. It can hide sinister bugs if you don't also heed compiler warnings.
This:
int x, y, z = 0;
is not the same as
int x = 0, y = 0, z = 0;
or
int x = 0;
int y = 0;
int z = 0;
In the first case only z
will be initialized while in the latter two cases - all three.
If value is not initialized its value is indeterminate and reading uninitialized variable is undefined behavior - and the fact that after reading it it appears to have value 0 is result of undefined behavior.
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