Search code examples
ccompound-literals

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


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


Solution

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