简体   繁体   中英

Function argument anonymous struct


Many of us know that this works:

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});
}

I have seen this many times, but now cannot find anything in C reference manual about it. Is this construct standard or implementation defined?

Also, that type casting is kinda odd, because it is more like "I will tell compiler how and what to allocate and how to arrange it" than "cast that type to this type". Will the data layout in memory of the argument passed to function will be exactly the same as of object created by struct data_s obj; ?

This is the compound literal .

I was introduced in C99 and there is no difference between it and other constants and literals.

From web:

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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