penfield.s
penfield.s

Reputation: 23

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...

Upvotes: 2

Views: 380

Answers (3)

LPs
LPs

Reputation: 16243

Only as an exercise:

  1. using a specific pattern for your union members
  2. taking care of update the code each time you update the union members
  3. Using a variable to trace the end of each member

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

Ian Abbott
Ian Abbott

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

Scott Hunter
Scott Hunter

Reputation: 49893

I see 2 ways to answer this question:

  1. Each union has only one size, so that would be the smallest size of it as well.
  2. If what you really wanted was the smallest size of the elements that make up the union, then compute the size of each element in isolation and take the minimum of those.

Upvotes: 3

Related Questions