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

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

    I'm going to go out on a limb here and say that there is a straight answer to this question, both for variable declarations and for parameter and return types, which is that the asterisk should go next to the name: int *myVariable;. To appreciate why, look at how you declare other types of symbol in C:

    int my_function(int arg); for a function;

    float my_array[3] for an array.

    The general pattern, referred to as declaration follows use, is that the type of a symbol is split up into the part before the name, and the parts around the name, and these parts around the name mimic the syntax you would use to get a value of the type on the left:

    int a_return_value = my_function(729);

    float an_element = my_array[2];

    and: int copy_of_value = *myVariable;.

    C++ throws a spanner in the works with references, because the syntax at the point where you use references is identical to that of value types, so you could argue that C++ takes a different approach to C. On the other hand, C++ retains the same behaviour of C in the case of pointers, so references really stand as the odd one out in this respect.

提交回复
热议问题