Blacksilver Blacksilver - 1 month ago 27
C Question

Return A union in C

So, I have a union:

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


(EDIT2: semicolin)

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

object_t foo(char ch){
object_t output;

if(ch == 'a'){ /* Could use a switch here. */
output.intVal = 1;
} else if(ch == 'b'){
output.charVal = 'A';
} else {
output.boolVal = false;
}

return output;
}


But this is rather messy. is there a easier way to do this?

EDIT:

something like:

object_t foo(char ch){
object_t output;

if(ch == 'a'){ /* Could use a switch here. */
return 1;
} else if(ch == 'b'){
return 'A';
} else {
return false;
}

//return output; //Derp, did not mean to leave this in.
}

Answer

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.