函数参数匿名结构

Function argument anonymous struct


我们中的许多人都知道这行得通:

struct data_s
{
    uint32_t p_1;
    uint32_t p_2;
    uint32_t p_3;
    uint32_t p_4;
};

void foo(struct data_s data)
{
    printf("p1: %d\r\n", data.p_1);
    printf("p2: %d\r\n", data.p_2);
    printf("p3: %d\r\n", data.p_3);
    printf("p4: %d\r\n", data.p_4);
}

int main(void)
{
    foo((struct data_s){
            .p_1 = 1,
            .p_2 = 2,
            .p_3 = 3,
            .p_4 = 4});
}

我已经看过很多次了,但是现在在 C 参考手册中找不到任何关于它的内容。此构建标准或实现是否已定义?

此外,该类型转换有点奇怪,因为它更像 "I will tell compiler how and what to allocate and how to arrange it" 而不是 "cast that type to this type"。传递给函数的参数在内存中的数据布局是否与 struct data_s obj; 创建的对象完全相同?

这是compound literal

我是在C99引入的,和其他常量、字面量没有区别

来自网络:

The compound literal expression constructs an unnamed object of the type specified by type and initializes it as specified by initializer-list.

The type of the compound literal is type (except when type is an array of unknown size; its size is deduced from the initializer-list as in array initialization).

The value category of a compound literal is lvalue (its address can be taken).

The unnamed object to which the compound literal evaluates has static storage duration if the compound literal occurs at file scope and automatic storage duration if the compound literal occurs at block scope (in which case the object's lifetime ends at the end of the enclosing block).