Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting a constant to a union

Tags:

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);
  return(1);
}

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!