Why is the asterisk before the variable name, rather than after the type?

后端 未结 12 1669
时光取名叫无心
时光取名叫无心 2020-11-22 08:53

Why do most C programmers name variables like this:

int *myVariable;

rather than like this:

int* myVariable;
12条回答
  •  忘了有多久
    2020-11-22 09:27

    A great guru once said "Read it the way of the compiler, you must."

    http://www.drdobbs.com/conversationsa-midsummer-nights-madness/184403835

    Granted this was on the topic of const placement, but the same rule applies here.

    The compiler reads it as:

    int (*a);
    

    not as:

    (int*) a;
    

    If you get into the habit of placing the star next to the variable, it will make your declarations easier to read. It also avoids eyesores such as:

    int* a[10];
    

    -- Edit --

    To explain exactly what I mean when I say it's parsed as int (*a), that means that * binds more tightly to a than it does to int, in very much the manner that in the expression 4 + 3 * 7 3 binds more tightly to 7 than it does to 4 due to the higher precedence of *.

    With apologies for the ascii art, a synopsis of the A.S.T. for parsing int *a looks roughly like this:

          Declaration
          /         \
         /           \
    Declaration-      Init-
    Secifiers       Declarator-
        |             List
        |               |
        |              ...
      "int"             |
                    Declarator
                    /       \
                   /        ...
               Pointer        \
                  |        Identifier
                  |            |
                 "*"           |
                              "a"
    

    As is clearly shown, * binds more tightly to a since their common ancestor is Declarator, while you need to go all the way up the tree to Declaration to find a common ancestor that involves the int.

提交回复
热议问题