0

As asked on my assignment earlier I had to just right two functions part (a) was regarding "enum" and part b was regarding "struct"

Now its asking me to create a union that can store either a. The enum in part(a) b. The struct in part(b) c. A single character.

i'm very confused.. What is this "either"?

Here I'm mentioning the code of part (a) & part (b)

a)

enum FavouriteFruits
{
    Cherries=4,
    Pears = 1,
    Berries = 2,
    Plums = 5
};

 int main (int argc, char* argv[])
{

    printf("Cherries are %d \n", Cherries);
    printf("Pears are %d \n" , Pears);
    printf("Berries are %d \n", Berries);
    printf("Plums are %d \n", Plums);

    return 0;
}

b)

struct realnumber
{
    float array [2][3];
    char* (*function)(int);
};
  • 3
    Have you read the explanation of what a `union` is in your textbook? It should be clear what they mean by "either". – Barmar Apr 13 '19 at 04:36
  • 1
    A union is similar to a struct, except all of its members share the same storage. So in general, only one member is active and valid at a time. See your textbook for examples. – Tom Karzes Apr 13 '19 at 04:38
  • Yes my friend. I've read the explanation and still I'm confused and that't the reason I posted this question.. I'm not playing friend. 2 @Barmar – Aly Ashar Apr 13 '19 at 04:39
  • Okay.. But why does it say "store either" .. Do I not have to code for all three of them? or just select one of these out of three? @TomKarzes – Aly Ashar Apr 13 '19 at 04:41
  • It means you can store any one of them at a time. At a later time, you can store a different one, at the expense of losing the previous one. A union can store one of its members at a time. There's no more to it than that. – Tom Karzes Apr 13 '19 at 06:02

1 Answers1

0

A union is a type that uses the same memory to hold a value that can be one of several different types.

union myUnion {
    enum FavouriteFruits ff;
    struct realnumber rn;
    char c;
};

You can now declare a variable of this type:

union myUnion u;

and assign to any of the members, just like assigning to a struct member.

u.c = 'a';
u.ff = Pears;

The difference from a struct is that they all share the same memory. When you assign to u.ff, it overwrites u.c. So you can only read from the same member that you last assigned to. It's your responsibility to keep track of which member that was. See How can a mixed data type (int, float, char, etc) be stored in an array? for a technique called a tagged union that can be used for this.

Barmar
  • 741,623
  • 53
  • 500
  • 612