1

I have looked into this post and explored the use cases of union. Every source is saying that it is memory efficient over structures, I understand this.

But confusion arises when you say:

"Variables of Union share same memory, when you change the value of one variable, then other's value gets changed, and only one variable is accessible at a time"

So why is there a need to declare union and its child variables, why can not I use 1 simple variable by allocating the biggest memory as union biggest variable?

Consider this example:

union {
   int length;
   int breadth;
   char status;
} dimension;

Versus

int dimension;  # Now this can store the highest value similar to length and breadth.
Gorka
  • 1,971
  • 1
  • 13
  • 28
Deepak
  • 667
  • 8
  • 16
  • `int length int; ` what language is it? – 0___________ Jul 19 '20 at 00:24
  • 2
    In this particular example, you're right. It becomes more challenging when the types are not all integers; consider `union foo { long int i; double d; char *s; };`. You can't safely store any one of them in any of the others. – Nate Eldredge Jul 19 '20 at 00:25
  • in this case it does not make any sense. But you will eventually get to the point (when you start to write more complex programs) when unions will become very handy. – 0___________ Jul 19 '20 at 00:25
  • Hi Nate, thanks for the answer. Yes, I looked into that example too. Can you please give one use case where input from the user gets dumped into these variables, and later we are taking any action on the basis of variable value? Basically I am looking for one end to end and simple use case :) Thanks – Deepak Jul 19 '20 at 00:30
  • 1
    As a silly example, imagine a data structure that needs to store information about a current or former employee. If they are a current employee we need to store their salary. If former, we need to store the reason they left as a string. You could have a data structure `struct employee { char *name; bool current; union more_info { int salary; char *departure_reason; }; };` – Nate Eldredge Jul 19 '20 at 00:36
  • 2
    Does this answer your question? [Purpose of Unions in C and C++](https://stackoverflow.com/questions/2310483/purpose-of-unions-in-c-and-c) – Andreas is moving to Codidact Jul 19 '20 at 01:37
  • 1
    @Deepak I made a polymorphic example for you – klutt Jul 19 '20 at 01:44
  • 1
    What is often done is to have a union of structures. Then you can do what this person has done: https://stackoverflow.com/questions/46155675/accessing-first-field-of-struct-in-a-union-of-structs – Jerry Jeremiah Jul 19 '20 at 01:47

2 Answers2

2

I think we use union when you are not clear about the type of the variable.

I used union when I convert assemble language to c code. Sometimes one variable used as an int variable and sometimes used as a pointer. At this time I used union.

union {
  int data;
  void* handle;
}

I hope it's helpful for your understanding.

Kungfu Frog
  • 81
  • 1
  • 8
2

So why is there a need to declare union and its child variables, why can not I use 1 simple variable by allocating the biggest memory as union biggest variable?

You could do that, but a union makes it much easier.

Your particular example does not make much sense, mostly because you have two of the same type, but also because all are integers. So let's take an example from the post you linked:

union {
  int i;
  float f;
} u;

This means that you can use u.i when you want to treat the memory as int or u.f if you want to treat it like a floatfloat.

So let's say you want to solve this without a union and just declare a variable "big enough". Which type do you pick? int is at least 16 bit, and float is at least 32 bit. So we pick a float then? Nope, because it might be the case that on the target system, an int is 64 bit and a float 32. So let's overdo things and pick the largest type that exists? Well, you could, but that kind of defeats the purpose of saving memory.

And how do we access them as different types if declared as variables? Consider this code:

float x;
int y = *(int*) x;

Should work nice, right? Nope, apart from the problem that sizes may vary, you will also run into problems with representations. There are a number of different ways of representing both integers and floats. You may also encounter problems with endianess.

You can mimic the behavior of unions without actually using them, but it will require A LOT of extra work. The resulting code is very likely to contain a lot of bugs, and is probably much slower and less portable too.

One use case is to achieve polymorphism. Here is a very simple example, and tbh, it does not look it make things much easier, but that's commonly the case with examples. Suppose we have this:

void print_float(float f)
{
    printf("Value: %f\n", f);
}

void print_int(int i)
{
    printf("Value: %d\n", i);
}

That could be replaced by this:

struct multitype {
    union {
        int i;
        float f;
    } data;
    enum { INT, FLOAT } type;
};

void print(struct multitype x)
{
    switch(x.type) {
    case INT:     printf("Value: %d\n", x.data.i); break;
    case FLOAT:   printf("Value: %f\n", x.data.f); break;
    }
}
klutt
  • 30,332
  • 17
  • 55
  • 95