Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing all variables in C in one line and uninitialized value

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?

like image 249
Ka-Wa Yip Avatar asked Dec 19 '22 10:12

Ka-Wa Yip


2 Answers

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 of a 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.

like image 172
StoryTeller - Unslander Monica Avatar answered Jan 21 '23 08:01

StoryTeller - Unslander Monica


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.

like image 39
Giorgi Moniava Avatar answered Jan 21 '23 09:01

Giorgi Moniava