Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C structure initialization

Tags:

c

structure

I got the following code from internet:

struct {
   int x;
   struct {
       int y, z;
   } nested;
} i = { .nested.y = 5, 6, .x = 1, 2 };

The result is:

i.nested.y = 2
i.nested.z = 6

But I don't know why,the article from the net doesn't give any explanation.

like image 341
hywl51 Avatar asked Jul 05 '26 11:07

hywl51


1 Answers

Non-designated initializers operate always on the next element in the structure. So the latest 2 operates on what comes after .x, which is .nested.y. In the same way the 6 goes for the nested.z.

If an initializer has several values for an element, the last in the list wins.

But if you have compiler that implements designated initializers, there should be no reason not to use them. The example that you are giving is very much far fetched and not of much educational value.

like image 64
Jens Gustedt Avatar answered Jul 07 '26 02:07

Jens Gustedt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!