Initialize struct without an assignment?

前端 未结 3 1191
无人共我
无人共我 2021-01-13 14:43

I could not find an answer to this on the Internet, so here is my question: Can I define a struct instance without assigning it to a local or global variable in C? E.g.:

3条回答
  •  鱼传尺愫
    2021-01-13 15:02

    Yes, you can use compound literals in C99 and later.

    return (struct A) { .b = 42 };
    

    You can even point to them:

    struct A *a = &(struct A) { .b = 42 };
    a->b = 43;
    

    These literals are "better" than string literals in that they are writable. The compiler may pool them if and only if you include const in the literal's type .

提交回复
热议问题