我正在进入C和我试验联盟。我的代码如下:关于联合和多个整数值
#include <stdio.h>
union date {
int year ;
char month;
char day ;
};
int main() {
union date birth;
birth.year = 1984;
birth.month = 7;
birth.day = 28;
printf("%d, %d, %d\n",birth.year, birth.month, birth.day);
// return 1820,28,28
return 0;
}
1984被写入二进制为0111 1100 0000
7被写入二进制如0110
28被写入二进制如0001 1100
我明白,因为工会,birth.year
的值为0111 0001 1100这是1820.但我不明白为什么birth.month
返回值28. 28.
我想你只能访问最后修改的值,不是吗? –
@SouravGhosh:这是一个棘手的问题。我将C标准解释为保证你可以使用工会来进行类型窜改(比如'memcpy()')。 – EOF
@ L.M你期望'month'包含什么? (没有双关语意,但你应该提及你期望看到的内容) – rustyx