声明时联合是否设置为零?
Is union set to zeroes when declared?
我在两台不同的机器上试过,结果都是零。这只是一个机会,它是垃圾吗?
#include <stdio.h>
int main()
{
typedef union { int x; } union1;
union1 u;
printf("%d\n", u.x);
}
我知道您未初始化的编译警告,因此,请不要包含有关该问题的答案或评论。我想知道以下哪种情况:
- 它依赖于编译器(如果是,请包括 gcc 的任何官方来源)
- 它总是垃圾,我很幸运在 两台 台不同的机器上找到 所有 个零。
- 始终为零(如果是,请提供任何官方来源)
如果未初始化,静态存储变量将被清零。自动变量不是。
声明具有自动存储持续时间的变量或聚合时,在明确为其赋值之前,它具有未定义的值。
u
具有自动存储持续时间,因为它是在函数范围内声明的,而不是显式声明的 static
.
C 标准,§ 6.7.9 p 10:
If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate.
有可能在现代系统上,您只是获取该地址内存中已有的内容,但这绝不是保证。
C99 标准第 6.7.8 节第 10 条:
If an object that has automatic storage duration is not initialized
explicitly, its value is indeterminate.
If an object that has static storage duration is not initialized
explicitly, then:
- if it has pointer type, it is initialized to a null pointer
- if it has arithmetic type, it is initialized to (positive or unsigned) zero
- if it is an aggregate, every member is initialized (recursively)
according to these rules
- if it is a union, the first named member is
initialized (recursively) according to these rules.
本质上,对于全局变量(那些在函数外定义的),它们保证为零。但是,对于在函数内部定义的变量,它是未定义的,可以是任何东西,具体取决于程序、您的编译器、您的系统和许多其他因素的预先存在的内存布局。
我在两台不同的机器上试过,结果都是零。这只是一个机会,它是垃圾吗?
#include <stdio.h>
int main()
{
typedef union { int x; } union1;
union1 u;
printf("%d\n", u.x);
}
我知道您未初始化的编译警告,因此,请不要包含有关该问题的答案或评论。我想知道以下哪种情况:
- 它依赖于编译器(如果是,请包括 gcc 的任何官方来源)
- 它总是垃圾,我很幸运在 两台 台不同的机器上找到 所有 个零。
- 始终为零(如果是,请提供任何官方来源)
如果未初始化,静态存储变量将被清零。自动变量不是。
声明具有自动存储持续时间的变量或聚合时,在明确为其赋值之前,它具有未定义的值。
u
具有自动存储持续时间,因为它是在函数范围内声明的,而不是显式声明的 static
.
C 标准,§ 6.7.9 p 10:
If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate.
有可能在现代系统上,您只是获取该地址内存中已有的内容,但这绝不是保证。
C99 标准第 6.7.8 节第 10 条:
If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate.
If an object that has static storage duration is not initialized explicitly, then:
- if it has pointer type, it is initialized to a null pointer
- if it has arithmetic type, it is initialized to (positive or unsigned) zero
- if it is an aggregate, every member is initialized (recursively) according to these rules
- if it is a union, the first named member is initialized (recursively) according to these rules.
本质上,对于全局变量(那些在函数外定义的),它们保证为零。但是,对于在函数内部定义的变量,它是未定义的,可以是任何东西,具体取决于程序、您的编译器、您的系统和许多其他因素的预先存在的内存布局。