Efficient way to return a union in C?
Asked Answered
I

1

6

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?

Ibby answered 3/10, 2019 at 21:8 Comment(1)
You mean how to initialize a union? I don't see anything tedious. You will have to assign all of the fields you need to assign. In one line or in 100 lines.Serous
U
10

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.

Underwriter answered 3/10, 2019 at 21:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.