首页 > 如何理解C中同时声明多变量的机制?

如何理解C中同时声明多变量的机制?

为了理解该机制,我做了实验:

int main(void) {
  int d = 3;
  int a = 1, b= 2, *c = &d;
  (int *) e = &a, f = &b;
  return 0;
}

编译成果返回

c.c: In function ‘main’:
c.c:4:11: error: ‘e’ undeclared (first use in this function)
   (int *) e = &a, f = &b;
           ^
c.c:4:11: note: each undeclared identifier is reported only once for each function it appears in
c.c:4:19: error: ‘f’ undeclared (first use in this function)
   (int *) e = &a, f = &b;

(int *) e = &a, f = &b; 为什么行不通?


(int *) e = &a, f = &b;

其实我也不是很清楚,不过根据错误返回信息,可以看到,(int*)其实被解析成了强制类型转换(本来就是这么着吧),所以错误信息是e未定义, 然后整体是一个逗号表达式。。


按照C++ Primer 关于变量定义的说法,类型可以分成两部分:一个是basic type,另外一部分是decorator。int, double, 还有甚至struct,class 属于basic type,定义基础类型。* 或者引用& 属于decorator,仅装饰用。

* 和 & 属于右结合(right associative)操作符,因为是和变量结合在一起的。所以书上一般都写作:

TYPE *var;

因此以上就很好理解,即便加了() 也会被忽略,*和第一个变量右结合,基础类型决定所有变量类型,装饰器只能装饰第一个变量。后两个不是指针。


C multiple single line declarations 说明了声明多变量的机制。

如果要声明比较特殊的类型时,比如指向 int 类型的指针,则应该要用到「声明符」(declarator),而不是靠原本的类型前缀。

比如同时声明多个指向 int 的指针时,则应该写为 int *a, *b, *c; 而 int *a, b, c 只会声明指向 int 类型的指针 a, 其它变量本身都属于 int 类型。

当然,用 typedef 也可以:

typedef int *iptr;
iptr x, y, z;

(int *) e = &a, f = &b; 之所以行不通,因为 (int *) 实际上是在声明返回 int 类型的函数指针(大概?)。


(int *) e = &a, f = &b;

表示对 e 做强制类型转换到指向 int 的指针,但是 e 未定义,所以会报错“‘e’ undeclared (first use in this function)", 并且类型转换是不能作为 lvalue 的,这根本不是一个赋值表达式。
因此这句中的“,”其实可以理解为“;”,即和下面是等价的。

(int *) e = &a;
f = &b;

那么显然 f 也是未定义的,所以会报错“‘f’ undeclared (first use in this function)”。
正确的赋值应该是

int *e = &a, *f = &b;

或者

typedef int *iptr;
iptr e = &a, f = &b;
【热门文章】
【热门文章】