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

后端 未结 2 1553
清歌不尽
清歌不尽 2021-01-14 07:30

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

2条回答
  •  时光取名叫无心
    2021-01-14 07:35

    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.

提交回复
热议问题