C 中冲突的类型和变量命名

标签 c gcc clang

我最近偶然发现了一个奇怪的代码结构,它导致 C 编译器进入一个奇怪的状态。我想解释为什么会发生这种情况。

这是我演示问题的小代码片段:

#include <stdlib.h>

typedef int type_t;

int main (void)
{
  int a = 10, b = 100;

  type_t *type_t = &a; // We name a variable with type name
  type_t *type_c = &b; // We define a variable with type_t

  return EXIT_SUCCESS;
}

这是 gcc 显示的错误信息:

#> gcc -Wall -Wextra -o sample sample.c 
sample.c: In function ‘main’:
sample.c:11:11: error: ‘type_c’ undeclared (first use in this function); did you mean ‘type_t’?
   type_t *type_c = &b;
           ^~~~~~
           type_t
sample.c:11:11: note: each undeclared identifier is reported only once for each function it appears in

或者,使用 clang:

#> clang -Wall -Wextra -o sample sample.c 
sample.c:11:11: error: use of undeclared identifier 'type_c'; did you mean 'type_t'?
  type_t *type_c = &b;
          ^~~~~~
          type_t
sample.c:10:11: note: 'type_t' declared here
  type_t *type_t = &a;
          ^
sample.c:11:10: error: invalid operands to binary expression ('type_t *' (aka 'int *') and 'type_t *')
  type_t *type_c = &b;
  ~~~~~~ ^~~~~~~
2 errors generated.

请注意,如果我们按如下方式修改代码,它可以正常编译:

int main (void)
{
  int a = 10, b = 100;

  type_t *type_c = &b; // We define a variable with type_t
  type_t *type_t = &a; // We name a variable with type name

  return EXIT_SUCCESS;
}

那么,现在我的问题!

错误似乎是由赋值运算符 '=' 的左值被误认为是 type_ttype_c 之间的乘法而产生的。由于 type_c 未知,它解释了错误消息。

但是,为什么我们会对左值产生这种混淆? type_t 指的是类型而不是变量,难道不是很明确吗?

我想这不是实现问题,因为 gccclang 的行为相同。但是,我真的很想知道这个问题的关键。

最佳答案

这是预期的正确行为。在 C 中,有多个 namespaces :标签、成员、标记和普通标识符。 typedef 名称位于普通标识符 namespace 中,变量名称也是如此。

你有:

type_t *type_t = &a; // We name a variable with type name
type_t *type_c = &b; // We define a variable with type_t

这里出现了三个type_t。第一个是 typedef 名称;没问题。第二个是新的变量名;没问题,但它隐藏(隐藏)了 typedef 名称;您不能再在当前代码块中引用类型 type_t。第三次出现指的是变量;你将一个整数指针乘以一个 undefined variable (并试图将结果用作左值来接收 b 的地址),这在很多层面上都是错误的。

当您颠倒这些行的顺序时,它工作正常,因为 type_c 被声明为 type_t * OK;然后 type_t 被定义为 type_t * 类型的变量,但是不能在当前 block 中对类型 type_t 进行进一步的引用(任何此类引用都是针对变量,而不是类型)。

请注意,如果 typedef 在函数内部,您将无法使用 type_t *type_t = &a; 隐藏它。参见 C11 §6.2.1 Scopes of identifiers .

关于C 中冲突的类型和变量命名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53507551/

相关文章:

c - c中的整数大小取决于什么?

c++ - 未声明未使用的变量。 gcc 取笑我?

c++ - CMake、VTK8 和 Embarcaderos Clang 编译器

clang scan-build 仅适用于 arch i386

c - Schönauer Triad 基准 - L1D 缓存不可见

c - 仅在使用 clang 10 编译时出现 strsep 之后的段错误

c - C语言中的For循环语法

c - Auriotouch,从频率FFT获取音符

比较、组合和确定字符串的长度?

c++ - 编译器会优化和重用变量吗