Consider the following C struct declaration containing types of animals
typedef enum Animals { DOG, CAT, LION, ELEPHANT, HIPPO } Animals;
typedef struct {
union {
struct {
Animals pet; /*!< Pet animals are stored at index 0 */
Animals zoo; /*!< Zoo animals are stored at index 1 */
};
Animals animals_list[2];
};
} AnimalsList;
I'd like to access the animals sometimes using the pet
member or zoo
member and sometimes to iterate over all animals using animals_list
. I am expecting that pet
will always be at index 0 of animals_list
and zoo
to be always at index 1 of animals_list
.
Is this assumption correct? Can this be considered undefined behavior? In particular I'm concerned about endianness difference across platforms.
I saw multiple questions regarding unions on stackoverflow but they all seems to use members of different size. My members have the same size and I'm trying to keep it that way.
union
for something that you want to access separately. Or is your intent just to understand the behaviour your described? – jweyrich Apr 2 '19 at 17:58struct
, but common C implementations will not, so the array will overlap thestruct
members as desired. Nonetheless, doing this is a bad idea. – Eric Postpischil Apr 2 '19 at 18:13struct Animal { enum Animals; enum Type; }
which stores twice as much, but is less confusing and more expandable. Then the number of pets and zoo animals doesn't have to be the same. – Neil Apr 2 '19 at 20:28Animals *animals_get_pet(AnimalsList *t) { return &t->animals_list[0]; } Animals *animals_get_zoo(AnimalsList *t) { return &t->animals_list[1]; }
– KamilCuk Apr 3 '19 at 23:21