Is it valid to have a pointer and a non pointer data type in a union?

98 Views Asked by At

Assuming we dereference correctly and use the integer right, is this a good programming practice?

union {
int x;
struct node * next;
};
2

There are 2 best solutions below

2
AnT stands with Russia On BEST ANSWER

Unions are rather low-level language feature. There are no meaningful reason for any restrictive "good programming practices" to exist with regards to which types can reside together in a union. The purpose of union is to "multiplex" memory usage: to save space by storing several unrelated objects with non-overlapping lifetimes in the same memory region.

If that's what you need - go for it.

Unions are sometimes used for raw memory reinterpretation (AKA type-punning). This usage of unions used to be illegal, until it was formally legalized in one of the late technical corrigendums to C99 standard. While it has its uses, type-punning can indeed be seen as questionable programming practice.

4
Yann Ramin On

Valid? Yes.

Good idea? Probably not. A pointer isn't even sizeof(int) on 64-bit, so this will lead to less-useful results.