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

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

    Something nobody has mentioned here so far is that this asterisk is actually the "dereference operator" in C.

    *a = 10;
    

    The line above doesn't mean I want to assign 10 to a, it means I want to assign 10 to whatever memory location a points to. And I have never seen anyone writing

    * a = 10;
    

    have you? So the dereference operator is pretty much always written without a space. This is probably to distinguish it from a multiplication broken across multiple lines:

    x = a * b * c * d
      * e * f * g;
    

    Here *e would be misleading, wouldn't it?

    Okay, now what does the following line actually mean:

    int *a;
    

    Most people would say:

    It means that a is a pointer to an int value.

    This is technically correct, most people like to see/read it that way and that is the way how modern C standards would define it (note that language C itself predates all the ANSI and ISO standards). But it's not the only way to look at it. You can also read this line as follows:

    The dereferenced value of a is of type int.

    So in fact the asterisk in this declaration can also be seen as a dereference operator, which also explains its placement. And that a is a pointer is not really declared at all, it's implicit by the fact, that the only thing you can actually dereference is a pointer.

    The C standard only defines two meanings to the * operator:

    • indirection operator
    • multiplication operator

    And indirection is just a single meaning, there is no extra meaning for declaring a pointer, there is just indirection, which is what the dereference operation does, it performs an indirect access, so also within a statement like int *a; this is an indirect access (* means indirect access) and thus the second statement above is much closer to the standard than the first one is.

提交回复
热议问题