3

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!
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
adengle
  • 227
  • 1
  • 8
  • 1
    Your brain hurts because you insist on using a style that's not consistent with the language. – user3386109 Jan 13 '16 at 04:24
  • It should be `int *myPtr;` and `int *myInt4, myInt5;` https://stackoverflow.com/a/398414/125507 – endolith Jul 27 '17 at 20:43
  • 1
    I should note that I've been coding in C++ for quite some time, and finally stumbled into this weirdness in the language. I've always left-aligned the asterisk because I think the pointer is part of the type. And it *is*! You can pass `int*` into templates, and `int*` can be the type of something. The only place this doesn't apply, afaik, is in variable declarators, where the pointer is part of the identifier! Even then, it's invisible if you only declare one variable. I get that it's because C works that way, but I think some brain-hurting is justified. – jpfx1342 Jan 28 '19 at 15:36

3 Answers3

5

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.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
1

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.

Chris Beck
  • 15,614
  • 4
  • 51
  • 87
0

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.

user3860869
  • 121
  • 1
  • 1
  • 6