简体   繁体   English

C中花括号的奇怪用法

[英]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...抱歉问了一个简单的问题,但我正在度假,正在阅读一本关于核心音频的书,而且我没有带 C 或 Objective C 的书......

What are the curly braces doing in this variable definition?这个变量定义中的花括号有什么作用?

MyRecorder recorder = {0};

Assuming that MyRecorder is a struct , this sets every member to their respective representation of zero ( 0 for integers, NULL for pointers etc.).假设MyRecorder是一个struct ,这MyRecorder每个成员设置为它们各自的零表示0表示整数, NULL表示指针等)。

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!)实际上,这也适用于所有其他数据类型,例如intdouble 、指针、数组、嵌套结构……,您可以想象的一切(感谢 pmg 指出这一点!)

UPDATE : A quote extracted from the website linked above, citing the final draft of C99:更新:从上面链接的网站中摘录的引用,引用了 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. [6.7.8.21] 如果花括号括起来的列表中的初始值设定项少于聚合的元素或成员,[...] 聚合的其余部分应隐式初始化,与具有静态存储持续时间的对象相同。

Its initializing all members of recorder structure to 0 according to C99 standard.它根据 C99 标准将recorder结构的所有成员初始化为0 It might seem that it initializes every bit of the structure with 0 bits.看起来它用0位初始化结构的每一位。 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

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.但是,其他的会自动初始化为 0,因为这是 C 标准要求做的。

If you put: MyRecorder recorder = {3};如果你把:MyRecorder recorder = {3};

The first element will be 3 and the others weill be 0.第一个元素将为 3,其他元素将为 0。

Unlike C++11, in C99 there has to be at least one element in initializer braces.与 C++11 不同,在 C99 中,初始化括号中必须至少有一个元素。

C++11 struct: C++11 结构:

MyRecorder recorder{};

C struct: C结构:

MyRecorder recorder = {0};

MyRecorder could be one of the following and you are attempting to initialize all the elements of that with zero MyRecorder可能是以下之一,您正在尝试用零初始化所有元素

typedef struct _MyRecorder1 {
    int i;
    int j;
    int k;
}MyRecorder1;

typedef int MyRecorder2[3];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM