为什么将指针(*)和数组([])符号绑定到变量名而不在变量声明中键入? [英] Why pointer (*) and array ([]) symbols are bound to variable name and not to type in variable declaration?
问题描述
关于C(和C ++的C子集)中的指针和数组声明的详细信息,关于SO的问题很多.
我对为什么感兴趣.
为什么当我们在一行中声明多个指针/数组时,必须在每个变量的前面放置*
,[]
吗?
There're a lot of questions on SO about details of pointer and array declarations in C (and C subset of C++).
I'm more interested in why.
Why do we have to put *
, []
in front of every variable when we declare several pointers/arrays in a row?
int *a, *b;
int c[1], d[1];
为什么我们必须在函数指针中的变量名之后/周围输入内容?
Why do we have to type out things after/around variable names in function pointers?
void (*foo_ptr)(int, int);
为什么,当甚至编译器都将这些内容作为类型的一部分识别并报告时,我们具有使许多新手感到困惑的功能吗?例如:function foo accepts int** but it was given int*
Why do we have this feature that confuses a lot of newcomers, when even compilers recognize and report these things as part of type? Ex: function foo accepts int** but it was given int*
我想我正在寻找它背后的直觉,从而导致以这种方式创建它,以便可以将其应用于对语言的理解.现在我看不到...
I guess I'm looking for intuition behind it that caused it being created this way, so that I can apply it to my understanding of the language. Right now I just don't see it...
推荐答案
Kernighan和Ritchie用 C编程语言,1978年,第90页:
Kernighan and Ritchie write, in The C Programming Language, 1978, page 90:
指针
px
的声明是新的.
int *px;
用作助记符;它表示组合*px
是int
,也就是说,如果px
出现在上下文*px
中,则它等效于类型int
的变量.实际上,变量声明的语法模仿了可能出现该变量的表达式的语法.这种推理在涉及复杂声明的所有情况下都是有用的.例如,
is intended as a mnemonic; it says the combination *px
is an int
, that is, if px
occurs in the context *px
, it is equivalent to a variable of the type int
. In effect, the syntax of the declaration for a variable mimics the syntax of expressions in which the variable might appear. This reasoning is useful in all cases involving complicated declarations. For example,
double atof(), *dp;
表示在表达式atof()
和*dp
中具有类型double
的值.
says that in an expression atof()
and *dp
have values of type double
.
因此,我们看到,在诸如int X, Y, Z
,X
,Y
和Z
的声明中,为我们提供了表达式的图片",例如b
,*b
,b[10]
,*b[10]
等.声明的标识符的实际类型是从图片得出的:由于*b[10]
是int
,因此b[10]
是指向int
的指针,所以b
是包含10个指向int
的指针的数组.
Thus, we see that, in declarations such as int X, Y, Z
, X
, Y
, and Z
give us "pictures" of expressions, such as b
, *b
, b[10]
, *b[10]
, and so on. The actual type for the declared identifier is derived from the picture: Since *b[10]
is an int
, then b[10]
is a pointer to an int
, so b
is an array of 10 pointers to int
.
这篇关于为什么将指针(*)和数组([])符号绑定到变量名而不在变量声明中键入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!