C 多个单行声明
当我在一行上声明多个变量时会发生什么?例如
int x, y, z;
全部都是整数。问题是下面语句中的 y 和 z 是什么?
int* x, y, z;
都是int指针吗?
What happens when I declare say multiple variables on a single line? e.g.
int x, y, z;
All are ints. The question is what are y and z in the following statement?
int* x, y, z;
Are they all int pointers?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
只有
x
是指向int的指针;y
和z
是常规整数。这是 C 声明语法中让一些人感到困惑的一个方面。 C 使用声明符的概念,它引入了所声明的事物的名称以及类型说明符未提供的附加类型信息。在声明中,
声明符是
*x
、y
和z
(这是 C 语法的一个意外,您可以编写int * x
或int *x
,这个问题是我推荐使用第二种风格的几个原因之一)。x
、y
和z
的 int 性由类型说明符int
指定,而指针x
的 -ness 由声明符*x
指定(IOW,表达式*x
的类型为int
) 。如果您希望所有三个对象都是指针,您有两种选择。您可以显式地将它们声明为指针:
或者您可以为 int 指针创建 typedef:
只需记住,声明指针时,
*
是变量名称的一部分,而不是类型。Only
x
is a pointer to int;y
andz
are regular ints.This is one aspect of C declaration syntax that trips some people up. C uses the concept of a declarator, which introduces the name of the thing being declared along with additional type information not provided by the type specifier. In the declaration
the declarators are
*x
,y
, andz
(it's an accident of C syntax that you can write eitherint* x
orint *x
, and this question is one of several reasons why I recommend using the second style). The int-ness ofx
,y
, andz
is specified by the type specifierint
, while the pointer-ness ofx
is specified by the declarator*x
(IOW, the expression*x
has typeint
).If you want all three objects to be pointers, you have two choices. You can either declare them as pointers explicitly:
or you can create a typedef for an int pointer:
Just remember that when declaring a pointer, the
*
is part of the variable name, not the type.在你的第一句话中:
它们都是
int
。然而,在第二个中:
只有
x
是指向int
的指针。y
和z
是普通的int
。如果您希望它们全部成为指向 int 的指针,您需要执行以下操作:
In your first sentence:
They are all
int
s.However, in the second one:
Only
x
is a pointer toint
.y
andz
are plainint
s.If you want them all to be pointers to
int
s you need to do:只有 x 是 int 指针。 Y 和 Z 将只是 int。
如果你想要三个指针:
Only x is an int pointer. Y and Z will be just int.
If you want three pointers:
重要的是要知道,在 C 中,声明模仿了用法。 * 一元运算符在 C 中是右关联的。因此,例如,在 int *x 中,x 是指向 int(或 int-star)的指针类型,而在 int x 中>, x 是 int 类型。
正如其他人也提到的,在 int* x, y, z; 中,C 编译器将 x 声明为 int-star,将 y 和 z 声明为整数。
It is important to know that, in C, declaration mimics usage. The * unary operator is right associative in C. So, for example in
int *x
x is of the type pointer to an int (or int-star) and inint x
, x is of type int.As others have also mentioned, in
int* x, y, z;
the C compiler declares x as an int-star and, y and z as integer.