【发布时间】:2022-11-10 18:30:00
【问题描述】:
我知道union 允许在同一个内存位置存储不同的数据类型。您可以定义具有许多成员的联合,但在任何给定时间只有一个成员可以包含值。考虑这个程序:
#include <stdio.h>
union integer {
short s;
int i;
long l;
};
int main() {
union integer I;
scanf("%hi", &I.s);
scanf("%d", &I.i);
scanf("%ld", &I.l);
printf("%hi - %d - %ld ", I.s, I.i, I.l );
}
假设我们输入值11、55、13,程序将作为输出
13 - 13 - 13,这里没问题。但是,如果我要创建 struct integer 类型的三个不同变量
#include <stdio.h>
union integer {
short s;
int i;
long l;
};
int main() {
union integer S;
union integer I;
union integer L;
scanf("%hi", &S.s);
scanf("%d", &I.i);
scanf("%ld", &L.l);
printf("%hi - %d - %ld ", S.s, I.i, L.l );
}
比所有值都将被保留。 怎么来的?通过使用三个变量,我实际上是在使用三个联合,每个联合只包含一个值吗?
【问题讨论】:
-
不同的联合是不同的变量
-
对,那是正确的。每个工会都独立于其他工会。您不必利用每个工会成员。