-5
int* p1, p2;

According to the C++ standard, p1 is a pointer yet p2 is not.

I just wonder why the C++ standard doesn't also define p2 as a pointer?

I think it is reasonable to do so. Because:

C++ is a strong-typing language. That is to say, given any type T, the statement T t1, t2; always guarantees t1 and t2 have the same type.

However, the fact that p1 and p2 don't have the same type breaks the rule, and seems counter-intuitive.

So, my question is: What's the rationale to make such a counter-intuitive rule as is? Just for backward compatibility?

xmllmx
  • 39,765
  • 26
  • 162
  • 323
  • 1
    What's all this nonsense about "strong typing" and "backward compatibility"? What's wrong with being able to define, for example, an int and a pointer to an int on the same line? – paulsm4 Sep 21 '13 at 03:31
  • "an int and a pointer to an int on the same line" should be considered as ill-style. I think. – xmllmx Sep 21 '13 at 03:33
  • 2
    @xmllmx Your way of writing the pointer qualifier adherent to the type name instead of the identifier is the ill style, rather. `int *p` is preferred over `int* p` for this exact reason (the `*` qualifies the name, not the type). –  Sep 21 '13 at 03:51
  • 2
    Just don't do that. Declaring multiple variables per line is considered bad practice. If you declare one per line this becomes a non issue. – Martin York Sep 21 '13 at 03:56

2 Answers2

3

int is the base type, * or & are prefix specifiers which are also called declarator operators. It means that * operates on the variable after it. And it is not a modifier for int. I think that is why.

CS Pei
  • 10,869
  • 1
  • 27
  • 46
2

The simple answer that won't help you much is that this is done for backwards compatibility with C, that has exactly the same syntax to define variables. The rationale for that design would have to come from the creators of C, and I don't really know it.

What I do know is that most coding guidelines I have used in different companies prohibited the definition of multiple variables in the same statement, and once you avoid that, everything becomes simple to read an maintain. The syntax for declarations in C and C++ is not really one of their strengths, but it is what it is.

David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489