Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 declarations / definitions use the T *name format, i.e., bind the * to the variable name. The pointer is thought of belonging to the variable, not the type.

In most C++ code I see, the format is T* name, i.e., it binds the * to the type of the variable . The pointer is thought of belonging to the type, not the variable. I myself, as a pure C++ coder, also use this format, as a pointer-to-type clearly (for me) belongs to the type, not the variable. (Incidently, even the C++ standard uses this format in the examples. :) )

Is there a (historic) reason for this? Has the way of thinking just changed when programmers started doing C++?

It would also be nice if a C coder (that uses the former format) could explain on why s/he uses it, and not the latter.

like image 991
Xeo Avatar asked Jun 23 '11 06:06

Xeo


2 Answers

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++.

like image 62
Omnifarious Avatar answered Nov 09 '22 05:11

Omnifarious


From Stroustrup's C++ Style and Technique FAQ.

A "typical C programmer" writes int *p; and explains it "*p is what is the int" emphasizing syntax, and may point to the C (and C++) declaration grammar to argue for the correctness of the style. Indeed, the * binds to the name p in the grammar.

A "typical C++ programmer" writes int* p; and explains it "p is a pointer to an int" emphasizing type. Indeed the type of p is int*. I clearly prefer that emphasis and see it as important for using the more advanced parts of C++ well.

like image 33
N.R.S.Sowrabh Avatar answered Nov 09 '22 05:11

N.R.S.Sowrabh