|
> int* p I very much prefer that syntax, because the '*' is part of the type, not part of the variable name. > You might never declare more that a single variable in a statement int a, *b, c, *d;
Yes, you can do that, and in fact if you want to declare multiple pointers on the same line, you are required to put a '*' in front of every pointer variable name.Personally, I've always considered this to be a defect of the language. Would it really be so awful to have to write instead: // Both are of type 'int'. Pretty straightforward.
int a, c;
// In my fantasy world, both of these would be of type 'pointer to int',
// but IRL b is a pointer and d is an int. fun!
int* b, d;
But of course that's not the language we have.I'd be very curious to know the motivation for requiring a '*' in front of each pointer variable name, as opposed to once with the type. So far the only ones I've thought of (not mutually exclusive) are: a) we REALLY love terseness, and b) ooh look at this clever hack I came up with for variable declaration syntax. |
I agree with you that this is an obvious mental model and it might be true for other languages, but this isn't the model that the C language has, which reveals in the fact that:
does not declare two pointers.You can see it like this: C does not have a way to declare a variable to be a pointer to int. In C you can only declare an expression with a variable to have the type int.
That's why I don't like this syntax especially for beginners. It is deceiving. It leads to people thinking it works differently than it really does and coming up with weird mental models. For example, that the unary '*'-operator has two meanings: dereference and declaring a pointer. Than they say a pointer should better be denoted by '&', because that's the address-of operator. But that's wrong, unary '*' always means dereference. You don't declare 'a' to have type 'int *', you declare '*a' to have the type 'int'!
It's the same with array syntax (and also with function pointers and really every declaration):
I agree that it doesn't cause problems for people who are experienced in the declaration rules of C, and it might never cause confusion if you never declare multiple variables in a line (I never do, because of diffability), but when teaching it leads to the wrong user model. Show 'int* a, b;' and people are confused, show 'int *a, b;' and it is obvious how it works.