为了理解该机制,我做了实验:
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;
为什么行不通?
C multiple single line declarations 说明了声明多变量的机制。
如果要声明比较特殊的类型时,比如指向 int 类型的指针,则应该要用到「声明符」(declarator),而不是靠原本的类型前缀。
比如同时声明多个指向 int 的指针时,则应该写为
int *a, *b, *c
; 而int *a, b, c
只会声明指向 int 类型的指针a
, 其它变量本身都属于 int 类型。当然,用 typedef 也可以:
(int *) e = &a, f = &b;
之所以行不通,因为(int *)
实际上是在声明返回 int 类型的函数指针(大概?)。