Initialize struct without an assignment?

前端 未结 3 1216
无人共我
无人共我 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:15

    Yes C99 provides compound literals for this (see it live):

    return (struct A) {  42 } ;
    

    which is covered in the draft C99 standard section 6.5.2.5 Compound literals and says:

    A postfix expression that consists of a parenthesized type name followed by a brace enclosed list of initializers is a compound literal. It provides an unnamed object whose value is given by the initializer list.84)

    and:

    The value of the compound literal is that of an unnamed object initialized by the initializer list. If the compound literal occurs outside the body of a function, the object has static storage duration; otherwise, it has automatic storage duration associated with the enclosing block.

    and provides several examples including:

    EXAMPLE 3 Initializers with designations can be combined with compound literals. Structure objects created using compound literals can be passed to functions without depending on member order:

    drawline((struct point){.x=1, .y=1}, (struct point){.x=3, .y=4});
    

    gcc also has a nice document on this in it's extension section since it supports this feature outside of C99 as well as clang.

提交回复
热议问题