views:

11

answers:

1

Hi, I used to initialize my structures in this way:

struct A a = {0};

This seems to work for me, however I was argued about ANSI C, C89, C99 standard.
Simply I couldn't find that in any documentation.
Could you help me with that?
Here's an example that this works for 'cl' (VS express 2008).

#include <stdio.h>
struct DATA
{
    int a;
    int b;
    char tab[3];
};


void main(void)
{
    struct DATA A;
    struct DATA B = {0};

    printf("A.a: %d, A.b: %d, A.tab: %s\n", A.a, A.b, A.tab);
    printf("B.a: %d, B.b: %d, B.tab: %s", B.a, B.b, B.tab);

};

>>>>>OUTPUT:
D:\N\workspace>test.exe

A.a: 4203600, A.b: 451445257, A.tab: ■   
B.a: 0, B.b: 0, B.tab:

This one shows that it initialize first with 1, rest with 0's.

include <stdio.h>
#include <stdlib.h>

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

ASDF A = {1};

int main()
{
    printf("a:%d,b:%d\n",A.a,A.b);
    return 0;
}

Output:
a:1,b:0
A: 

You are right, this always work. The relevant section in the C99 draft N1256 is 6.7.8 (Initialization):

21. If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

Objects of static storage duration are initialised to zero (paragraph 10 of the same section).

The ANSI standard is shorter, but similar in 3.5.7:

If there are fewer initializers in a list than there are members of an aggregate, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

schot