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

后端 未结 10 876
梦谈多话
梦谈多话 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:26

    C declarations follow the same rules (eg precedence) as expressions. In fact, it's perfectly valid to consider a declaration like

    int *foo;
    

    as declaring the type of the expression *foo (ie the indirection operator applied to foo) as int instead of foo as being of type int*.

    However - as other already pointed out - in C++ its common to think of types as a seperate, and - due to templates - modifyable entity, and thus it makes sense to use a declaration like

    int* foo;
    
    0 讨论(0)
  • Because Bjarne had the benefit of hindsight: he realized that the C declarator syntax was "an experiment that failed" (read: the C declarator syntax is retarded). The rest has already been answered by others.

    0 讨论(0)
  • I don't think you are correct about your distinction,

    There's C++ code in the T * style.

    There's C code in the T* style.

    I think it's just a matter of personal preference of the project participants.

    0 讨论(0)
  • 2021-01-07 22:30

    If I were to hazard a guess, I would say it's because C++ people are more likely to consider type information to be a thing in and of itself because templates make it possible to manipulate types programatically at compile time. They are also much less likely to declare several variables in the same declaration.

    The T* style focuses the type information in one place and makes it stand out, and the confusion that would be introduced by something like T* foo, bar; with this syntax is a non-issue if you never declare two variables in the same statement.

    Personally, I find the T* style to be really obnoxious and dislike it immensely. The * is part of the type information, it's true, but the way the compiler parses it makes it actually attached to the name, not the type. I think the T* way obscures something important that's happening.

    In my observations, it seems like I'm a rarity in the C++ community. I've noticed the same thing you have about what style is the most popular.

    To be clear, of course, either style works in either language. But I do notice the same thing you do, that one style tends to be a bit more common with C code, and the other a bit more common with C++.

    0 讨论(0)
  • 2021-01-07 22:30

    In K&R they use the type *name notation, so may be that's where many C programmers got it.

    0 讨论(0)
  • 2021-01-07 22:36

    The reason why C programmers tend to use one style while C++ programmers use the other style is quite simple: Kernighan & Ritchie used the "C style" in their book, while Stroustrup used the "C++ style" in his book.

    0 讨论(0)
提交回复
热议问题