gpt4 book ai didi

c - 为什么 union 中的成员名称可以与 C 中的 typedef 名称相同?

转载 作者:行者123 更新时间:2023-11-30 20:34:11 25 4
gpt4 key购买 nike

我在用于 8 位 MCU 应用程序的 SiLabs IDE 附带的“compiler_defs.h”中找到了下面的定义。我做了一些搜索工作,它似乎与 namespace 和标识符可见性问题有关。 C 中使用了 5 个 namespace (引用: Name Spaces ):

  1. 声明标签
  2. 结构体、 union 和枚举标记
  3. 组织或 union 的成员
  4. 普通标识符
  5. 类型定义名称

一个例子是:

struct student {
char student[20];
int class;
int id;
} student;

我对上面的示例没问题,但我仍然对下面的代码感到困惑,那么为什么 typedef 名称可以与 union 定义中的成员名称相同?您能解释一下吗?谢谢。

“compiler_defs.h”的代码摘录:

typedef unsigned char U8;
typedef unsigned int U16;
typedef unsigned long U32;

typedef signed char S8;
typedef signed int S16;
typedef signed long S32;

typedef union UU16
{
U16 U16; // [typedef name] [member variable name]
S16 S16;
U8 U8[2];
S8 S8[2];
} UU16;

typedef union UU32
{
U32 U32;
S32 S32;
UU16 UU16[2];
U16 U16[2];
S16 S16[2];
U8 U8[4];
S8 S8[4];
} UU32;

创建我自己的 main.c 并包含compiler_defs.h:

U16 U16; // this line in main.c cause compiler error: redefinition in VS2015, WHY?

最佳答案

好吧,你回答了你自己的问题:

  1. Statement labels
  2. Structure, union, and enumeration tags
  3. Members of structures or unions
  4. Ordinary identifiers
  5. Typedef names

这些是单独的命名空间,即一个命名空间中的名称不会与另一个命名空间中的相同名称发生冲突。对于您的情况:

U16 U16; // [typedef name] [member variable name]

第一个 U16 位于列表中的命名空间 #5 中。第二个位于命名空间 #3 中。独立的命名空间,因此名称可以相同而不会冲突。

关于c - 为什么 union 中的成员名称可以与 C 中的 typedef 名称相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43134404/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com