简体   繁体   English

C 中结构的默认初始化

[英]Default initialization for a struct in C

I want to do something like this in plain C:我想在普通 C 中做这样的事情:

struct data_msg {
    uint8_t id = 25;
    uint8_t       data1;
    uint32_t      data2;
}

I need the id to be set to 25 by default so that when I create an instance of the struct, the id is already set to 25, like this:我需要将 id 默认设置为 25,这样当我创建结构的实例时,id 已经设置为 25,如下所示:

struct data_msg      tmp_msg;
printf("ID: %d", tmp_msg.id); // outputs ID: 25

Is there a way to do this in C? C有没有办法做到这一点? I know it can be done in C++, but have not figured a way in C.我知道可以在C++中完成,但在C中还没有想出办法。

Doing this in C will throw errors:在 C 中这样做会抛出错误:

struct data_msg { uint8_t id = 25; }

Unfortunately, you can't, but if you do this a lot, you could create a constant that you use for initialization:不幸的是,你不能,但如果你经常这样做,你可以创建一个用于初始化的常量:

struct data_msg {
    uint8_t       id;
    uint8_t       data1;
    uint32_t      data2;
};

const struct data_msg dm_init = {.id = 25};

int main(void) {
    struct data_msg var = dm_init;  // var.id is now 25, data1 = 0, data2 = 0
    // ...
}

The C standard does not provide any feature for this. C 标准没有为此提供任何功能。 You may set initial values when defining an object, but there is no provision for setting default or initial values when defining a type.您可以在定义 object 时设置初始值,但在定义类型时没有规定设置默认值或初始值。

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

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