Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it the correct way to initialize array? [duplicate]

Tags:

arrays

c

Here is one not-so-common way of initializing the array:

 int a[3] = {[2] 5, [0] 10, [1] 15};

Used this array in the program,

#include <stdio.h>

int main() {
    //code
    int a[3] = {[2] 5, [0] 10, [1] 15};
    printf("a[0] = %d  a[1] = %d   a[2] = %d\n", a[0], a[1], a[2]);
    return 0;
}

Output:

a[0] = 10  a[1] = 15   a[2] = 5

Online Compiler Link: http://code.geeksforgeeks.org/4onQAI

So, I have a question:

Is it the correct way to initialize array?

like image 679
msc Avatar asked Aug 23 '16 10:08

msc


2 Answers

Close. The correct way is as follows:

int a[3] = {[2] = 5, [0] = 10, [1] = 15};

This is a designated initializer, which allows you to initialize specified elements. Any elements not specified are set to 0.

This is specified in section 6.7.9 of the C standard.

The syntax you show is a non-standard extension supported by some compilers, specifically GCC. If you were to compile with -pedantic, you would get the following warning:

warning: obsolete use of designated initializer without ‘=’

like image 119
dbush Avatar answered Sep 22 '22 06:09

dbush


Your code snippet uses an obsolete syntax for this designated initializer:

int a[3] = {[2] = 5, [0] = 10, [1] = 15};

An alternative syntax for this that has been obsolete since GCC 2.5 but GCC still accepts is to write ‘[index]’ before the element value, with no ‘=’. (reference)

Omitting = is not standard, and should not be used for new development.

like image 45
Sergey Kalinichenko Avatar answered Sep 25 '22 06:09

Sergey Kalinichenko