Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C struct initialization using labels. It works, but how?

I found some struct initialization code yesterday that threw me for a loop. Here's an example:

typedef struct { int first; int second; } TEST_STRUCT; void testFunc() {     TEST_STRUCT test = {         second: 2,         first:  1     };     printf("test.first=%d test.second=%d\n", test.first, test.second); } 

Surprisingly (to me), here's the output:

-> testFunc test.first=1 test.second=2 

As you can see, the struct gets initialized properly. I wasn't aware labeled statements could be used like that. I've seen several other ways of doing struct initialization, but I didn't find any examples of this sort of struct initialization on any of the online C FAQs. Is anybody aware of how/why this works?

like image 309
Andrew Cottrell Avatar asked Oct 21 '09 14:10

Andrew Cottrell


People also ask

How are structs initialized in C?

Structure members can be initialized using curly braces '{}'.

How are structs initialized?

When initializing a struct, the first initializer in the list initializes the first declared member (unless a designator is specified) (since C99), and all subsequent initializers without designators (since C99)initialize the struct members declared after the one initialized by the previous expression.

Is it possible to initialize structure members while defining a structure?

Que: Can we initialize structure members within structure definition? No! We cannot initialize a structure members with its declaration, consider the given code (that is incorrect and compiler generates error).


2 Answers

Here is the section of the gcc manual which explains the syntax of designated initializers for both structs and arrays:

In a structure initializer, specify the name of a field to initialize with '.fieldname =' before the element value. For example, given the following structure,

 struct point { int x, y; }; 

the following initialization

 struct point p = { .y = yvalue, .x = xvalue };  

is equivalent to

 struct point p = { xvalue, yvalue };  

Another syntax which has the same meaning, obsolete since GCC 2.5, is 'fieldname:', as shown here:

 struct point p = { y: yvalue, x: xvalue }; 

The relevant page can be found here.

Your compiler should have similar documentation.

like image 157
sigjuice Avatar answered Oct 31 '22 20:10

sigjuice


These are neither labels nor bitfields.

This is a syntax to initialize struct members dating back to the days before C99. It is not standardized but available in e.g. gcc.

typedef struct { int y; int x; } POINT; POINT p = { x: 1, y: 17 }; 

In C99, syntax for initializing specific struct members has been introduced for the first time in a standard, but it looks a little differently:

typedef struct { int y; int x; } POINT; POINT p = { .x = 1, .y = 17 }; 
like image 31
ndim Avatar answered Oct 31 '22 19:10

ndim