Why is it thought of 'T *name' to be the C way and 'T* name' to be the C++ way?

后端 未结 10 881
梦谈多话
梦谈多话 2021-01-07 22:18

Note: This question is about the position of the asterisk (*).

In most C code I see (e.g., in Beej\'s guide to network programming), all variable declar

10条回答
  •  逝去的感伤
    2021-01-07 22:48

    Just to throw some controversy into the matter:

    • C++ users commonly state that one declaration per line makes it okay to put the asterisk on the type (the left). int* a; int* b;
    • Both C and C++ are parsed with the asterisk attached to the name (on the right). int *a;
    • C++ preprocessors often move the asterisk to the left. C preprocessors move it to the right.
    • In either language, putting it on the left will look weird for declaring multiple variables of the same type in the same statement. int* a, * b, * c;
    • There are some syntactic elements that look stupid with it on the left. int* (* func)().

    There are other elements of C that are incorrectly used, such as const, which belongs on the right too! int const a;. This is commonly put on the left of the type, despite belonging to the type to its left. Many compilers have to be modified to handle this usage. In C++ you can observe this is conformed to with constant methods, as the compiler can't deduce for you if it's put on the left: int A::a() const. This also breaks down with nested usage of const, restricted and friends with such declarations as int const *. Conventional usage of const would suggest this is a constant pointer to an integer, but that's actually int *const.

    tl;dr

    You've all been doing it wrong all along, put everything on the right.

提交回复
热议问题