Why pointer (*) and array ([]) symbols are bound to variable name and not to type in variable declaration?

会有一股神秘感。 提交于 2020-02-04 03:57:10

问题


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);

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...


回答1:


Kernighan and Ritchie write, in The C Programming Language, 1978, page 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.

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.




回答2:


Why do we have to put *, [] in front of every variable when we declare several pointers/arrays in a row?

The answer would be: explicit is better than implicit. In such a case we can even declare different types on the same row, int *a, *b, c; and so on, in another case it would be too messy. The same true for the second question.



来源:https://stackoverflow.com/questions/59436290/why-pointer-and-array-symbols-are-bound-to-variable-name-and-not-to-typ

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!