Reputation: 233
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!
Upvotes: 3
Views: 844
Reputation: 121
int* myInt4, myInt5
; // an int pointer then an integer. Brain hurts!
This is just style, compiler will interpret it correctly. Theoretically, You can put * any where.
Type* variable;
Type * variable;
Type *variable;
And It can be read as:
int* myInt4, myInt5
;` // A pointer variable (myInt4) and a variable (myInt5) of type int.
Upvotes: 0
Reputation: 134326
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.
Upvotes: 5
Reputation: 16204
What kind of answer are you expecting? This is just how C works. If you don't like it, Bjarne Stroustrup (creator of C++) agrees with you, and recommends to avoid doing the thing you did in the last line.
It makes sense to the makers of C, and also, its common to put the *
next to the variables rather than next to the type so that it's less confusing:
int *myInt4, myInt5; // an int pointer then an integer.
If you use clang-format
to format your source-code, this is style-option PointerAlignment
, and the option you want is PAS_Right
for that.
Upvotes: 1