为什么指针(*)和数组([])符号绑定到变量名,而不是键入变量声明?
Why pointer (*) and array ([]) symbols are bound to variable name and not to type in variable declaration?
关于 C(和 C++ 的 C 子集)中指针和数组声明的详细信息,SO 上有很多问题。
我对 为什么 .
更感兴趣
为什么连续声明多个pointers/arrays时,每个变量前面都要加上*
、[]
?
int *a, *b;
int c[1], d[1];
为什么我们必须在函数指针中输入 after/around 变量名?
void (*foo_ptr)(int, int);
为什么我们有这个让很多新手感到困惑的特性,甚至编译器也将这些东西识别并报告为类型的一部分?例如:function foo accepts int** but it was given int*
我想我是在寻找它背后导致它以这种方式创建的直觉,以便我可以将它应用到我对语言的理解中。现在我只是看不到它...
Why do we have to put *, [] in front of every variable when we declare
several pointers/arrays in a row?
答案是:显式优于隐式。在这种情况下,我们甚至可以在同一行上声明不同的类型,int *a, *b, c;
等等,在另一种情况下就太乱了。第二题同理
Kernighan 和 Ritchie 在 The C Programming Language 中写道,1978 年,第 90 页:
The declaration of the pointer px
is new.
int *px;
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;
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
是指向 int
.
的 10 个指针的数组
关于 C(和 C++ 的 C 子集)中指针和数组声明的详细信息,SO 上有很多问题。
我对 为什么 .
更感兴趣
为什么连续声明多个pointers/arrays时,每个变量前面都要加上*
、[]
?
int *a, *b;
int c[1], d[1];
为什么我们必须在函数指针中输入 after/around 变量名?
void (*foo_ptr)(int, int);
为什么我们有这个让很多新手感到困惑的特性,甚至编译器也将这些东西识别并报告为类型的一部分?例如:function foo accepts int** but it was given int*
我想我是在寻找它背后导致它以这种方式创建的直觉,以便我可以将它应用到我对语言的理解中。现在我只是看不到它...
Why do we have to put *, [] in front of every variable when we declare several pointers/arrays in a row?
答案是:显式优于隐式。在这种情况下,我们甚至可以在同一行上声明不同的类型,int *a, *b, c;
等等,在另一种情况下就太乱了。第二题同理
Kernighan 和 Ritchie 在 The C Programming Language 中写道,1978 年,第 90 页:
The declaration of the pointer
px
is new.
int *px;
is intended as a mnemonic; it says the combination
*px
is anint
, that is, ifpx
occurs in the context*px
, it is equivalent to a variable of the typeint
. 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;
says that in an expression
atof()
and*dp
have values of typedouble
.
因此,我们看到,在 int X, Y, Z
、X
、Y
和 Z
等声明中,为我们提供了表达式的“图片”,例如 b
、*b
、b[10]
、*b[10]
等。声明的标识符的实际类型来自图片:由于 *b[10]
是一个 int
,那么 b[10]
是一个指向 int
的指针,所以 b
是指向 int
.