Reputation: 23
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...
Upvotes: 2
Views: 380
Reputation: 16243
Only as an exercise:
you can do something like below
#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <inttypes.h>
struct s1
{
uint8_t member;
uint8_t len;
};
struct s2
{
uint16_t member;
uint8_t len;
};
struct s3
{
uint32_t member;
uint8_t len;
};
typedef union u1
{
struct s1 m1;
struct s2 m2;
struct s3 m3;
}UNION_TEST;
#define RETRIEVE_MEMBER(memberNum) m##memberNum
#define test(unionName, memberName) offsetof(unionName, memberName.len)+sizeof(uint8_t)
int main(void)
{
printf("sizeof = %zu\n", test(UNION_TEST, RETRIEVE_MEMBER(1)));
printf("sizeof = %zu\n", test(UNION_TEST, RETRIEVE_MEMBER(2)));
printf("sizeof = %zu\n", test(UNION_TEST, RETRIEVE_MEMBER(3)));
}
Upvotes: 2
Reputation: 17503
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.
Upvotes: 2
Reputation: 49893
I see 2 ways to answer this question:
Upvotes: 3