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

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

    People who prefer int* x; are trying to force their code into a fictional world where the type is on the left and the identifier (name) is on the right.

    I say "fictional" because:

    In C and C++, in the general case, the declared identifier is surrounded by the type information.

    That may sound crazy, but you know it to be true. Here are some examples:

    • int main(int argc, char *argv[]) means "main is a function that takes an int and an array of pointers to char and returns an int." In other words, most of the type information is on the right. Some people think function declarations don't count because they're somehow "special." OK, let's try a variable.

    • void (*fn)(int) means fn is a pointer to a function that takes an int and returns nothing.

    • int a[10] declares 'a' as an array of 10 ints.

    • pixel bitmap[height][width].

    • Clearly, I've cherry-picked examples that have a lot of type info on the right to make my point. There are lots of declarations where most--if not all--of the type is on the left, like struct { int x; int y; } center.

    This declaration syntax grew out of K&R's desire to have declarations reflect the usage. Reading simple declarations is intuitive, and reading more complex ones can be mastered by learning the right-left-right rule (sometimes call the spiral rule or just the right-left rule).

    C is simple enough that many C programmers embrace this style and write simple declarations as int *p.

    In C++, the syntax got a little more complex (with classes, references, templates, enum classes), and, as a reaction to that complexity, you'll see more effort into separating the type from the identifier in many declarations. In other words, you might see see more of int* p-style declarations if you check out a large swath of C++ code.

    In either language, you can always have the type on the left side of variable declarations by (1) never declaring multiple variables in the same statement, and (2) making use of typedefs (or alias declarations, which, ironically, put the alias identifiers to the left of types). For example:

    typedef int array_of_10_ints[10];
    array_of_10_ints a;
    

提交回复
热议问题