Search code examples
cunionsdereference

Why must I use the structure dereference operator rather than just cast a union


Why do the following two calls to f give different output?

#include"stdio.h"

typedef union {
  int value_int;
  char value_char;
} my_union_t;

void f(int x)
{
  printf("x: %d\n", x);
}

void main()
{
  my_union_t u;
  u.value_int = 7;
  my_union_t * p_u = &u;
  f( (int) p_u );
  f( p_u->value_int );
}

Output:

x: -393095784
x: 7

Solution

  • As the other answer points out, you do not want to cast the pointer to an int. You need a dereference.

    The compiler will not let you do this:

    f((int) u);

    However, you can get the address, cast to an integer pointer, and then dereference:

    f(*(int *) &u)

    Indeed u.value_int == *(int *) &u.

    That seems to be the closest you can get to "casting a union to an integer".