Answer the question
In order to leave comments, you need to log in
What's the point of the union type?
What's the point of the union type? I know that it is well, I have not seen anywhere where it is used. Then what is its meaning?
Answer the question
In order to leave comments, you need to log in
What's the point of the union type? I know that it is well, I have not seen anywhere where it is used.
In order to store data of different types in one volume.
For example, in x32 Int is 4 bytes, and Double is 8 bytes
Doing
union Some {
int i;
double a;
};
struct STRX {
int j;
Some v;
}
Sometimes you need to save memory in this way.
The most common use I've seen is structures in files.
You can make generic storage objects.
Example:
#include <stdio.h>
struct a {
int a, b, c;
};
struct b {
double a, b, c, d;
};
struct c {
char s[100];
};
struct d {
int a, b, c;
double n[10];
};
union x {
struct a a;
struct b b;
struct c c;
struct d d;
};
typedef struct {
enum { A, B, C, D } type;
union x value;
} Obj;
int main(void)
{
Obj objects[100], *pobj;
int n;
int i;
objects[0].type = A;
objects[0].value.a.a = 1;
objects[0].value.a.b = 2;
objects[0].value.a.c = 3;
objects[1].type = B;
objects[1].value.b.a = 1.5;
objects[1].value.b.b = 2.5;
objects[1].value.b.c = 3.5;
objects[1].value.b.d = 4.5;
objects[2].type = C;
sprintf(objects[2].value.c.s, "abc");
objects[3].type = A;
objects[3].value.a.a = 4;
objects[3].value.a.b = 5;
objects[3].value.a.c = 6;
n = 4;
for (i = 0; i < n; i++) {
pobj = objects + i;
switch (pobj->type) {
case A:
printf("A: %d %d %d\n",
pobj->value.a.a,
pobj->value.a.b,
pobj->value.a.c);
break;
case B:
printf("B: %g %g %g %g\n",
pobj->value.b.a,
pobj->value.b.b,
pobj->value.b.c,
pobj->value.b.d);
break;
case C:
printf("C: %s\n", pobj->value.c.s);
break;
case D:
printf("D: %g\n", pobj->value.d.n[0]);
break;
}
}
return 0;
}
[[email protected] c]$ .ansi t.c -o t
[[email protected] c]$ ./t
A: 1 2 3
B: 1.5 2.5 3.5 4.5
C: abc
A: 4 5 6
[[email protected] c]$
I won't give you a direct answer, but I'll give you something to think about. It's a paradox, but programming languages still implement the goto operator, despite the fact that it has been marked as obsolete / deprecated for 10 years and generally not taken into hands. What for? perhaps for backward compatibility, perhaps in the bowels of the implementation it is used somewhere. Don't use? Well, then don't use it. What's the problem then? Yes, the Pareto principle has not been canceled - 80% of users use only 20% of the functionality.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question