Reputation: 2141
Sorry for the simple question but I'm on vacation reading a book on core audio, and don't have my C or Objective C books with me...
What are the curly braces doing in this variable definition?
MyRecorder recorder = {0};
Upvotes: 31
Views: 3613
Reputation: 759
Unlike C++11, in C99 there has to be at least one element in initializer braces.
C++11 struct:
MyRecorder recorder{};
C struct:
MyRecorder recorder = {0};
Upvotes: 0
Reputation: 57690
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
Upvotes: 9
Reputation: 95358
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.
Upvotes: 26
Reputation: 796
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.
Upvotes: 5
Reputation: 16627
MyRecorder
could be one of the following and you are attempting to initialize all the elements of that with zero
typedef struct _MyRecorder1 {
int i;
int j;
int k;
}MyRecorder1;
typedef int MyRecorder2[3];
Upvotes: 0