Is it not possible to initalize more than 4 variables at once?

Viewed 87
void main() {
    int a, b, c, d, e = 0;

    printf("\n%d", a);
    printf("\n%d", b);
    printf("\n%d", c);
    printf("\n%d", d);
    printf("\n%d", e);
}

output:

16
0
10818512
0
0

For some reason a is always equal to 16 although I initialize it to 0.

c on the other hand always changes its value when I rerun the code. Why does this happen?

I feel like I am missing out on something important here.

4 Answers

Only e is initialized to zero. All other variables aren't initialized. See Initialization for an explanation

Initialization
For each declarator, the initializer, if not omitted, may be one of the following:

...

Implicit initialization
If an initializer is not provided:

  • objects with automatic storage duration are initialized to indeterminate values (which may be trap representations)

So, if you want to initialize each variable, you must provide an initializer for each of them, e.g.

int a = 0, b = 0, c = 0, d = 0, e = 0;

a is always equal to 16 although I initialize it to 0

No, you do not.

This line

int a, b, c, d, e = 0;

initialises only e to 0.

All other variables stay uninitialised. Printing might invoke undefined behaviour. The values printed are just something, garbage, undefined.

To initialise a as well, do

int a = 0, b, c, d, e = 0;

Is it not possible to initalize more than 4 variables at once?

It is not even possible to (explicitly) initialise more than one variables at once.

All your variables except for e are uninitialized. You need to explicitly initialize them using the assignment operator =:

int a = 0, b = 0, c = 0, d = 0, e = 0;
...

Your printf() statements except the one involving e invoke undefined behavior.

You shouldn't rely on undefined behavior. It might appear as if it's working normally and it might not.

All variables in this declaration

int a, b, c, d, e = 0;

are not initialized except the last variable e. They would be zero-initialized if they had the static storage duration. However these variables are local variables with the automatic storage duration and are not initialized by the compiler implicitly.

You need to initialize each variable like

int a = 0, b = 0, c = 0, d = 0, e = 0;

Another approach if you want to initialize all variables by zero at once is to enclose the variables in a structure like

struct { int a, b, c, d, e; } s = { 0 };

In this case all variables will be initialized by zero. You can access them like for example s.a or s.b and so on.

Here is a demonstrative program.

#include <stdio.h>

int main(void) 
{
    struct { int a, b, c, d, e; } s = { 0 };

    printf( "s.a = %d\n", s.a );
    printf( "s.b = %d\n", s.b );
    printf( "s.c = %d\n", s.c );
    printf( "s.d = %d\n", s.d );
    printf( "s.e = %d\n", s.e );

    return 0;
}

Its output is

s.a = 0
s.b = 0
s.c = 0
s.d = 0
s.e = 0
Related