Initialize the first element of the structure or the entire structure?

all:
      C:

struct A  
{
    int a;
    int b;
};

A aa = {0};  

Does this statement initialize aa.a only or initialize all struture? Or is the behavior dependent on the compiler?
Thanks in advance!

+5
source share
4 answers

From the standard ( N1570 )

6.7.9 Initialization

...
10 , , , . , , , :
- , ; - , ( ) ; - , () , ;
- , () , ;
...
21 , , , , , , , , .

, aa.a 0 - , aa.b 0 - .

+1
One more ex:
struct A  
{
    int a;
    int b;
};

struct A aa = {5}; 

, aa.b 0. , 0.

+4

C99, 6.7.8.17, ( , a) :

, , . , , : , .

""

A aa = {.b = 0};

, .

+1

aa.a ?

Take a look at the example below, initializing the structure with {3}, similar to initializing with {3.0}.

Therefore, in your program, when you initialize with {0}, you actually initialize both a and b (the whole structure), with {0,0}

#include<stdio.h>

typedef struct A  
{
    int a;
    int b;
}a;

int main()
{
a aa = {3};
printf("\na1 = %d",aa.a);
printf("\nb1 = %d",aa.b);

a bb = {3,0};
printf("\na2 = %d",bb.a);
printf("\nb2 = %d",bb.b);

}
+1
source

All Articles