Search code examples
cside-effectsvariable-initialization

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?


Solution

  • 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.