penfield.s penfield.s - 3 months ago 8
C Question

Is it possible to find out the smallest size of a C union

The size of a C union(sizeof()) is the size of its largest element.

However, is there any trick to find out what might be the smallest size of the union programmably?

I meant something along the line of how offsetof MACRO is implemented...

Answer

If I understand correctly, you want to find the size of the smallest member of a union type without declaring a variable of that type, and without referring to the type of the member. The following trick to get the size of a member will probably work, but is a little on the dodgy side:

#define membersize(type, member) sizeof(((type *)0)->member)

You'll have to compute the size of each member individually to determine which is the smallest, so if someone adds a new member to the union, you'll have to alter the code that determines the smallest member size to account for it.

Comments