Don't get me wrong, I love C/C++ and pointers. I know how to use them, but I have a bone to pick with the "standard" syntax for pointer declaration.
This is not meant to be opinion-based, I am not asking which is better. I am asking why each one is used, and how the system interprets each one.
Also, while I am asking from the view of pointers, this can equally be applied to references.
1. int *p;
over int* p;
I know they are the same thing, but the majority of code I've seen uses int *p;
. This is tutorials, documentation, and quite a lot of other stackoverflow users. What is the preference for attaching the *
to the variable name? While many places use that syntax, I have seen int* p;
used for the documentation of function parameters, and compiler messages, so clearly the type is noted as int*
to the program. However, this doesn't agree with points 2. and 3.
To me it is clear that int* p;
declares a variable p of type pointer-to-int. However, int *p;
feels almost like a dereference of some unknown p being declared as an integer. Obviously that is nonsensical so there's no problem reading it as a pointer type, it's just unintuitive.
While I say the dereference is nonsense, it could still be ambiguous to new users in cases like:
int *p = 0x00123456;
, which is the declaration of a pointer-to-int vs.
*p = 5;
, which is the assignment of an int.
This first part may seem to be a duplicate of other questions, but I am not asking the difference, I understand that int* p;
and int *p;
are identical.
2. int* p, i;
declares a pointer-to-int and an int, but int *p, *pi;
declares 2 pointers-to-ints
The second one definitely looks like some nonsensical dereference with variables of type int, whereas the first shows the type to be int*
. And why does it even allow int* p, i;
as a declaration of different types in one line?
3. Const specifier (and other similar things)
A const int*
declares a pointer-to-(const int)
Therefore int*
isn't truly being treated as the datatype. If it was, this would be treated as a const (pointer-to-int).
I also don't like how const applies to the thing on it's left, but that's another story ツ
I hope I've explained my concerns well enough, if not please ask me for clarification.
In the end, I understand that this is kinda just preference and style and with a little practice it's easy to read any of this, but I would still love an explanation for the different styles.