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

后端 未结 12 1775
时光取名叫无心
时光取名叫无心 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:22

    Because the * in that line binds more closely to the variable than to the type:

    int* varA, varB; // This is misleading
    

    As @Lundin points out below, const adds even more subtleties to think about. You can entirely sidestep this by declaring one variable per line, which is never ambiguous:

    int* varA;
    int varB;
    

    The balance between clear code and concise code is hard to strike — a dozen redundant lines of int a; isn't good either. Still, I default to one declaration per line and worry about combining code later.

提交回复
热议问题