Can you initialize only a few members of a C array already in your definition?

Asked

Viewed 80 times

8

I know you can do this:

int a[5] = { 0, 3, 8, 0, 5 };

or

int a[5];
a[1] = 3;
a[2] = 8;
a[4] = 5;

Can you do the same in just one line, already in the definition? IE, you can initialize only a few elements?

1 answer

11


There’s a syntax for this:

int a[5] = { [1] = 3, [2] = 8, [4] = 5 };

I put in the Github for future reference.

It can even be in any order. This syntax is the same as making the assignment after the declaration.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.