Placement of the asterisk in pointer declarations

前端 未结 13 1157
闹比i
闹比i 2020-11-22 04:36

I\'ve recently decided that I just have to finally learn C/C++, and there is one thing I do not really understand about pointers or more precisely, their definition.

13条回答
  •  一生所求
    2020-11-22 05:23

    In my opinion, the answer is BOTH, depending on the situation. Generally, IMO, it is better to put the asterisk next to the pointer name, rather than the type. Compare e.g.:

    int *pointer1, *pointer2; // Fully consistent, two pointers
    int* pointer1, pointer2;  // Inconsistent -- because only the first one is a pointer, the second one is an int variable
    // The second case is unexpected, and thus prone to errors
    

    Why is the second case inconsistent? Because e.g. int x,y; declares two variables of the same type but the type is mentioned only once in the declaration. This creates a precedent and expected behavior. And int* pointer1, pointer2; is inconsistent with that because it declares pointer1 as a pointer, but pointer2 is an integer variable. Clearly prone to errors and, thus, should be avoided (by putting the asterisk next to the pointer name, rather than the type).

    However, there are some exceptions where you might not be able to put the asterisk next to an object name (and where it matters where you put it) without getting undesired outcome — for example:

    MyClass *volatile MyObjName

    void test (const char *const p) // const value pointed to by a const pointer

    Finally, in some cases, it might be arguably clearer to put the asterisk next to the type name, e.g.:

    void* ClassName::getItemPtr () {return &item;} // Clear at first sight

提交回复
热议问题