Search code examples
cunions

Can I check if a Union-Member is set?


Having this union and stucts:

tydef union{
  TYPE1 t1;
  TYPE2 t2;
  TYPE3 t3;
}myunion;

typedef struct{
   uint8 ID;
   uint8 value;
}TYPE1;

typedef struct{
   uint8 ID;
   uint8 flag;
   long value;
}TYPE2;

I would like to execute a function like this:

CheckIfSet(&myunion.t1);

which works somewhat like this:

CheckIfSet(void *test){
  if (test.ID != NULL) then{
   return TRUE;
  }
  return FALSE;
}

Before executing this check, I am executing another function, which should result in the setup of myunion.t1 - but I need to check if it did happen.


Solution

  • No. You have to keep track of which field of a union is active. The backing memory of the union is shared across its fields, so setting one may affect the value of another.

    Also, don't forget that accessing an inactive field of a union results in undefined behavior.