Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Odd use of curly braces in C

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}; 
like image 902
John Avatar asked Jan 05 '12 15:01

John


People also ask

Are curly brackets necessary in C?

Curly braces indicates the block of statements in C programming language. The function in C has braces in its syntax. But one can put braces where logically related statements are written. A single statement in loop or if-else block need not be written within braces.

Is it necessary to use curly braces after the for statement?

If the number of statements following the for/if is single you don't have to use curly braces. But if the number of statements is more than one, then you need to use curly braces.

What are curly brackets used for in math?

Braces or curly brackets { } are used when the domain or range consists of discrete numbers and not an interval of values. If the domain or range of a function is all numbers, the notation includes negative and positive infinity . If the domain is all positive numbers plus 0, the domain would be written as .

What is the significance of curly braces in string handling?

As for me, curly braces serve as a substitution for concatenation, they are quicker to type and code looks cleaner.


2 Answers

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.

like image 124
Niklas B. Avatar answered Sep 17 '22 11:09

Niklas B.


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 
like image 42
Shiplu Mokaddim Avatar answered Sep 18 '22 11:09

Shiplu Mokaddim