Efficient way to return a union in C?

Viewed 1309

I have a function that returns a union, which the caller knows how to process. Is there an efficient 1-line way to return a union? What I do now:

typedef union { int i; char *s; double d; } FunnyResponse;
FunnyResponse myFunc () {
    // Tedious:
   FunnyResponse resp; 
   resp.d = 12.34;
   return resp;
}
int main () {
   printf ("It's this: %g\n", myFunc().d);
}

This compiles and runs however I'd like to have a single "return" line if possible. Any ideas?

1 Answers

You can use C99's designated initializers and compound literals:

return (FunnyResponse){ .d = 12.34 };

For ANSI C89 (Microsoft's C compiler), you'll have to do what you're doing now to get the same effect.

Related