The following code:

#include <stdio.h>

typedef union {
   int   n;
   char *s;
} val_t;

int main(void) {
  val_t v1,v2;

  v1 = (val_t)"Hello World";
  v2 = (val_t)10;

  printf("%s %d\n", v1.s, v2.n);

compiles and executes correctly with gcc. If one tries to cast a constant for which there's not a suitable field in the union, an error message is produced.

Looking at the (C99) standard, though, I've not been able to locate the section where this behaviour is described. Hence, my question:

Does the C standard guarantee that I can cast a constant to a union type, provided that the union type has a field with a compatible type?

or, in other words:

Is ((val_t)10) a valid rvalue of type val_t?

It would also be interesting to know if this behaviour is supported by other compilers (or at least MS Visual C++). Does anybody know?

EDIT: Casting to a union is a GCC extension, so it's not a good idea to use it.

Thanks to Maurits and Neil! I didn't think about using -pedantic to check!

Was it helpful?


In GNU C language extensions casting to a union is marked as an extension to the C standard. So most probably you won't find it in the C99 or any other C standard. The IBM C compiler supports this extension as well.


[neilb@GONERIL NeilB]$ gcc -Wall -pedantic sw.c
sw.c: In function 'main':
sw.c:11: warning: ISO C forbids casts to union type
sw.c:12: warning: ISO C forbids casts to union type
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow