Can I return a struct by initializing it inside a return in ANSI C?

Question:

Good morning everyone, I would like to know if I can do something like this…

typedef struct Result
{
   int low, high, sum;
} Result;

Result teste(){
   return {.low = 0, .high = 100, .sum = 150};
}

I know this wouldn't be the right way, but is there a way to do it or do I have to create a temporary variable in the function to receive the values ​​and then return it?

Answer:

Copies (with my translation) of Ouah's response on the English Stack Overflow .

You can do this using a compound literal :

Result test(void)
{
    return (Result) {.low = 0, .high = 100, .sum = 150};
}

(){} is the operator for compound literal that was introduced with version C99.

Scroll to Top