加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

struct和union name碰撞

发布时间:2020-12-16 10:07:22 所属栏目:百科 来源:网络整理
导读:我写了一个简单的测试程序并尝试使用它: union FLT { ... };struct FLT { ... }; 但编译器抱怨命名冲突. 因为在C中你需要为你的标签名称使用struct和union,为什么它们会发生碰撞? 我的意思是当我们想要声明一个名为num的stuct FLT类型的变量时,我们会使用
我写了一个简单的测试程序并尝试使用它:

union FLT { ... };
struct FLT { ... };

但编译器抱怨命名冲突.

因为在C中你需要为你的标签名称使用struct和union,为什么它们会发生碰撞?

我的意思是当我们想要声明一个名为num的stuct FLT类型的变量时,我们会使用它

struct FLT num;

当我们想要使用一个名为diffnum的变量时,我们会使用union FLT

union FLT diffnum;

那么为什么编译器无法区分它们呢?

顺便说一下,如果你需要知道,我测试了MinGW和VC.

UPDATE

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;

我正在使用此代码进行一些浮点运算测试.

解决方法

它们发生冲突,因为所有“标记类型”共享一个标记的命名空间.

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).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读