C Pointers – Why Asterisk in Pointer Declaration is Identifier-Specific

c++pointerssyntaxtypes

Silly question, but trying to grasp the underlying mechanics/philosophy to solidify my understanding.

int myInt; // declares a variable of type integer, named myInt. Intuitive.
int* myPtr; // declares a variable of type pointer-to-integer. Also intuitive.

int myInt2, myInt3; // two more integer variables.. yay!! This makes sense.
// so the pattern is [type] [identifier] <,more-identifiers>;

int* myInt4, myInt5; // an int pointer then an integer. Brain hurts!

Best Answer

TL;DR - that is how C syntax is designed to work.

The * is considered attached to the variable, because, it defines the type of the variable, not the datatype. The type of an object is supposed to be a property of the object itself, so it makes sense to consider the identifier of the property is associated with the object(variable).

To clarify, by saying int * p;, we mean to say, p is a variable of type pointer which points to an int. So, it makes sense to attach the * to the variable, rather than to the datatype.