C 编程:联合
C Programming : Unions
此程序将输出显示为
0 3 1
main()
{
union status {
int a;
int b;
int c;
};
union status std1, std2, std3;
printf("%d %d %d\n", std1, std2, std3);
return 0;
}
已在 Dev C++ 中测试。可能
0 3 1
不能是垃圾值。请告诉我。
您正在显示单位化数据。从任何定义来看,它都是垃圾 - 可能是运行时链接后的一些剩余物。
首先,让我告诉你,当使用%d
作为参数时,你需要访问联合的成员(类型int
),你不能传递联合本身。在当前状态下,任何符合标准的编译器都会尝试通过
之类的消息警告您
format ‘%d’ expects argument of type ‘int’, but argument 3 has type ‘union status’ [-Wformat=]
因为传递不兼容类型的参数会导致 undefined behavior。
之后,对于你看到的值,是不确定的值。你不可能有任何特定的输出。
在您的例子中,std1
、std2
、std3
都是自动局部变量,除非明确初始化,否则它们包含不确定的值。引用 C11
,章节 §6.7.9
If an object that has automatic storage duration is not initialized explicitly, its value is
indeterminate. [...]
逻辑思考,你从来没有把任何东西放在这里,你希望检索什么?
也就是说,这会导致 undefined behavior,因为类型可以有陷阱表示并且地址从未被占用,因此使用该值调用 UB。
未初始化的变量具有不确定的值 - 只是不知道它的值是多少。有一个支持变量的有效内存地址,它有一些垃圾内容。
并注意它是 UB(未定义的行为),即使初始化已正确完成。 @BLUEPIXY
此程序将输出显示为
0 3 1
main()
{
union status {
int a;
int b;
int c;
};
union status std1, std2, std3;
printf("%d %d %d\n", std1, std2, std3);
return 0;
}
已在 Dev C++ 中测试。可能
0 3 1
不能是垃圾值。请告诉我。
您正在显示单位化数据。从任何定义来看,它都是垃圾 - 可能是运行时链接后的一些剩余物。
首先,让我告诉你,当使用%d
作为参数时,你需要访问联合的成员(类型int
),你不能传递联合本身。在当前状态下,任何符合标准的编译器都会尝试通过
format ‘%d’ expects argument of type ‘int’, but argument 3 has type ‘union status’ [-Wformat=]
因为传递不兼容类型的参数会导致 undefined behavior。
之后,对于你看到的值,是不确定的值。你不可能有任何特定的输出。
在您的例子中,std1
、std2
、std3
都是自动局部变量,除非明确初始化,否则它们包含不确定的值。引用 C11
,章节 §6.7.9
If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. [...]
逻辑思考,你从来没有把任何东西放在这里,你希望检索什么?
也就是说,这会导致 undefined behavior,因为类型可以有陷阱表示并且地址从未被占用,因此使用该值调用 UB。
未初始化的变量具有不确定的值 - 只是不知道它的值是多少。有一个支持变量的有效内存地址,它有一些垃圾内容。
并注意它是 UB(未定义的行为),即使初始化已正确完成。 @BLUEPIXY