How can I pass a struct compound literal to a function as argument?
Asked Answered
A

1

7

Here is a struct that I have:

typedef struct 
{
    float r, g, b;
} color_t;

I'd like to pass a compound literal of this struct to a function as argument, like this:

void printcolor(color_t c)
{
    printf("color is : %f %f %f\n", c.r, c.g, c.b);
}

printcolor({1.0f, 0.6f, 0.8f});

However, this gives me an error:

error: expected expression before '{' token

Antibiotic answered 27/3, 2021 at 12:48 Comment(1)
printcolor((color_t) {1.0f, 0.6f, 0.8f}); Don't be fooled by the cast-like syntax. It's not a cast, it's still a compound literal.Weinshienk
A
5

A compound literal in C must have the type specified (using 'cast-like' syntax) before the brace-enclosed initializer list. So, as mentioned in the comments, you should change your function call to:

printcolor((color_t){1.0f, 0.6f, 0.8f});
Akvavit answered 27/3, 2021 at 12:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.