Blacksilver Blacksilver - 1 year ago 60
C Question

Return A union in C (but make it look nice)

So, I have a union:

typedef union {
int intVal;
char charVal;
bool boolVal;
} myUnion_t;

And I have a function,
, (in the same file as the latter union) which will return
I obviously could do:

myUnion_t foo(int n){
myUnion_t rtn;

if(n == 0){
rtn.intVal = 1;
} else if(n == 1){
rtn.charVal = 'b';
} else {
rtn.boolVal = false;

return rtn;

But this is rather messy; my CDO doesn't like it. Is there a nicer way to do this, something like:

myUnion_t foo(int n){
if(n == 1){
return 1;
} else if(n == 2){
return 'b';
} else {
return false;

EDIT: Okay, unions are inherently messy. Thanks for your help, I'll just do it the normal way :)

Answer Source

Although you cannot return a value of a union member in place of a union itself, you could use compound literals of C99 to avoid declaring the union at the top and setting its fields outside initializer:

typedef union object_t {
    int intVal;
    char charVal;
    _Bool boolVal;
} object_t;

object_t foo(char ch){
    switch(ch) {
        case 'a': return (object_t) { .intVal = 4 };
        case 'b': return (object_t) { .charVal = 'b' };
        default:  return (object_t) { .boolVal = true };

The reason you need to use compound literal is that the type by itself is insufficient to identify the member of a union that you would like to be assigned.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download