结构和联合名称冲突
struct and union name collision
我写了一个简单的测试程序并尝试使用这个:
union FLT { ... };
struct FLT { ... };
但是编译器抱怨命名冲突。
因为在 C 中你需要使用 struct
和 union
作为你的标签名称,为什么它们会冲突?
我的意思是当我们想要声明一个名为 num
的 stuct FLT
类型的变量时,我们会使用
struct FLT num;
并且当我们想要使用类型为 union FLT
的名为 diffnum
的变量时,我们将使用
union FLT diffnum;
那么为什么编译器不能区分它们呢?
顺便说一句,我测试了 MinGW 和 VC,如果你需要知道的话。
更新
union FLOAT {
float value;
unsigned int bits;
unsigned char bytes[4];
};
struct FLOAT {
unsigned int sign;
unsigned int exponent;
unsigned int significand;
};
union FLOAT num;
struct FLOAT num_parts;
我正在使用这段代码做一些浮点运算测试。
它们会发生冲突,因为所有 "tagged types" 标签共享同一个命名空间。
C11 6.2.3 Name spaces of identifiers (N1570 Draft)
If more than one declaration of a particular identifier is visible at
any point in a translation unit, the syntactic context disambiguates
uses that refer to different entities. Thus, there are separate name
spaces for various categories of identifiers, as follows:
- label names (disambiguated by the syntax of the label declaration and use);
- the tags of structures, unions, and enumerations (disambiguated by following any of the keywords struct, union, or enum);
- the members of structures or unions; each structure or union has a separate name space for its members (disambiguated by the type of the
expression used to access the member via the . or -> operator);
- all other identifiers, called ordinary identifiers (declared in ordinary declarators or as enumeration constants).
我写了一个简单的测试程序并尝试使用这个:
union FLT { ... };
struct FLT { ... };
但是编译器抱怨命名冲突。
因为在 C 中你需要使用 struct
和 union
作为你的标签名称,为什么它们会冲突?
我的意思是当我们想要声明一个名为 num
的 stuct FLT
类型的变量时,我们会使用
struct FLT num;
并且当我们想要使用类型为 union FLT
的名为 diffnum
的变量时,我们将使用
union FLT diffnum;
那么为什么编译器不能区分它们呢?
顺便说一句,我测试了 MinGW 和 VC,如果你需要知道的话。
更新
union FLOAT {
float value;
unsigned int bits;
unsigned char bytes[4];
};
struct FLOAT {
unsigned int sign;
unsigned int exponent;
unsigned int significand;
};
union FLOAT num;
struct FLOAT num_parts;
我正在使用这段代码做一些浮点运算测试。
它们会发生冲突,因为所有 "tagged types" 标签共享同一个命名空间。
C11 6.2.3 Name spaces of identifiers (N1570 Draft)
If more than one declaration of a particular identifier is visible at any point in a translation unit, the syntactic context disambiguates uses that refer to different entities. Thus, there are separate name spaces for various categories of identifiers, as follows:
- label names (disambiguated by the syntax of the label declaration and use);
- the tags of structures, unions, and enumerations (disambiguated by following any of the keywords struct, union, or enum);
- the members of structures or unions; each structure or union has a separate name space for its members (disambiguated by the type of the expression used to access the member via the . or -> operator);
- all other identifiers, called ordinary identifiers (declared in ordinary declarators or as enumeration constants).