Where does the * go?

This is a more amusing than functional debate I enter into from time to time.  On a line where you declare a pointer type in C++, where should the * go? 

  1. Next to the type (i.e. Type* p1;)
  2. Next to the variable name  (i.e. Type *p1;)
  3. Who cares

For the moment lets ignore #3 (after all they don't care).  I'm a firm believer in #1.  After all * is a part of the type of the variable, not the name and therefore should be closer to the type. 

#2 believers disagree with this notion.  They believe the * is a part of the individual variable's type and not the actual type.  This is technically correct and can be demonstrated with the following code

  Type* p1, p2;

The type of p2 is of course Type and not Type*. Therefore they argue, #2 is the superior way

This is true but I'm also a firm believer in don't declare multiple variables in a single declaration statement while coding in C++ unless the type has a user defined constructor.  Namely to avoid situations just like this. 

Comments (5)
  1. Will says:

    This inherent ambiguity in C++ is a great example of why more modern, or, rarely, older (FORTH, for instance) languages are usually a better choice for new software projects.

  2. R Caloca says:

    I’m all for #1; and I think you should declare one variable per line, makes it clearer (and easier to remove).

  3. Koush says:

    Hehe, yeah this always used to bug me in C++.

    On one hand it should go with the type. On the other hand, when doing multiple variable declarations, the * only applies to the first instance, and needs to be specified per variable (a flaw in C++ in my opinion).

    But I finally had my opinion confirmed, and this question answered with the introduction of C# and unsafe code:

    "char * foo, bar;" declares two variables, both of which are of type char* (C++ multiple pointer type declarations are flawed!). And upon typing the semicolon, the C# autoformatting left aligns your * against the char to produce "char* foo, bar;".

  4. snuchia@statsoft.com says:

    I liked it char *foo in C and had a hard time adapting but have come to believe in C++ it is best to avoid defining more than one object on a line.  I’ve therefore moved into the T* p camp.  With automated style checkers now ubiquitous and C++ allowing declarations interspersed with statements I now believe it best to forget about T *p and any declarations involving commas.  Make it a style rule and enforce it automatically and be happy.

    One good reason to prefer this more modern view is for direct tranlation between smart and ordinary pointers.  You can’t do that if the * isn’t treated as part of the type.

Comments are closed.

Skip to main content