Odd use of curly braces in C

Its initializing all members of recorder structure to 0 according to C99 standard. It might seem that it initializes every bit of the structure with 0 bits. But thats not true for every compiler.

See this example code,

#include<stdio.h>

struct s {
    int i;
    unsigned long l;
    double d;
};

int main(){
    struct s es = {0};
    printf("%d\n", es.i);
    printf("%lu\n", es.l);
    printf("%f\n", es.d);
    return 0;
}

This is the output.

$ ./a.out 
0
0
0.000000

It is an initialization of a structure.


Assuming that MyRecorder is a struct, this sets every member to their respective representation of zero (0 for integers, NULL for pointers etc.).

Actually this also works on all other datatypes like int, double, pointers, arrays, nested structures, ..., everything you can imagine (thanks to pmg for pointing this out!)

UPDATE: A quote extracted from the website linked above, citing the final draft of C99:

[6.7.8.21] If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, [...] the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.


Actually, it don't initliaze all the elements of the structure, just the first one. But, the others are automatically initialized with 0 because this is what the C standard ask to do.

If you put: MyRecorder recorder = {3};

The first element will be 3 and the others weill be 0.