How to initialize a struct in accordance with C programming language standards

I want to initialize a struct element, split in declaration and initialization. This is what I have:

typedef struct MY_TYPE {
  boolean flag;
  short int value;
  double stuff;
} MY_TYPE;

void function(void) {
  MY_TYPE a;
  ...
  a = { true, 15, 0.123 }
}

Is this the way to declare and initialize a local variable of MY_TYPE in accordance with C programming language standards (C89, C90, C99, C11, etc.)? Or is there anything better or at least working?

Update I ended up having a static initialization element where I set every subelement according to my needs.


In (ANSI) C99, you can use a designated initializer to initialize a structure:

MY_TYPE a = { .flag = true, .value = 123, .stuff = 0.456 };

Edit: Other members are initialized as zero: "Omitted field members are implicitly initialized the same as objects that have static storage duration." (https://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html)


You can do it with a compound literal. According to that page, it works in C99 (which also counts as ANSI C).

MY_TYPE a;

a = (MY_TYPE) { .flag = true, .value = 123, .stuff = 0.456 };
...
a = (MY_TYPE) { .value = 234, .stuff = 1.234, .flag = false };

The designations in the initializers are optional; you could also write:

a = (MY_TYPE) { true,  123, 0.456 };
...
a = (MY_TYPE) { false, 234, 1.234 };

I see you've already received an answer about ANSI C 99, so I'll throw a bone about ANSI C 89. ANSI C 89 allows you to initialize a struct this way:

typedef struct Item {
    int a;
    float b;
    char* name;
} Item;

int main(void) {
    Item item = { 5, 2.2, "George" };
    return 0;
}

An important thing to remember, at the moment you initialize even one object/ variable in the struct, all of its other variables will be initialized to default value.

If you don't initialize the values in your struct, all variables will contain "garbage values".

Good luck!

链接地址: http://www.djcxy.com/p/60874.html

上一篇: 用户界面术语:登录与登录

下一篇: 如何根据C编程语言标准初始化结构