4

I have noticed that in C++, a pointer can be declared using two different types of indentation (if that's the right word I'm looking for):

//Space followed by asterisk with variable name
char *pointer;

//Asterisk followed by space and then variable name
char* pointer;

Does the position of the asterisk affect anything about the pointer? If so, in what situations would I need to use one type of indentation over the other?

Ben
  • 1,299
  • 3
  • 17
  • 37
  • 1
    It is only a readability question. The blank in either position is optional. If you declare more than one variable together, the second way becomes seriously misleading: `char* pointer, notApointer;` Personally, I strongly dislike declaring more than one variable together so I prefer `char* pointer;` – JSF Dec 01 '15 at 19:43
  • Since `char*` is not a token and `*pointer` is not a token, they must both be equivalent to these four tokens: `char`, `*`, `pointer`, `;`. – David Schwartz Dec 01 '15 at 19:50

4 Answers4

10

No the whitespacing does not have any effect on the pointer declaration, but there is a bug in the C/C++ grammar (well, officially its a feature, but I don't know anyone who likes the behaviour), where this declaration

char* pointer, pointer2;

leaves pointer with the type of char* and pointer2 with the type of char. Because of this, many people prefer to write it down as

char *pointer, *pointer2;
char *pointer, not_pointer;

to make it clearer, that the "pointerness" is part of the name, not type.

anatolyg
  • 26,506
  • 9
  • 60
  • 134
Xarn
  • 3,460
  • 1
  • 21
  • 43
  • I took the liberty to edit this answer to reduce confusion. I hope I didn't spoil anything. – anatolyg Dec 01 '15 at 19:58
  • It's not a bug and it's even useful, I'll say, because it allows you to do: `int i = 10, *ptr = &i`. It works because pointers are _compound_ types: while you can have multiple compound types (ptrs, refs) in a declaration you can't have different types. Is it misleading, though? Yeah. – edmz Dec 01 '15 at 20:03
3

No, the asterisk position has no effect on the declaration of a pointer.

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
Fantastic Mr Fox
  • 32,495
  • 27
  • 95
  • 175
3

As long as the asterisk comes after the type and before the variable name, the spacing has no effect:

char *pointer;

Is the same as:

char      *             pointer;
anatolyg
  • 26,506
  • 9
  • 60
  • 134
Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122
0

In compound types like pointers, asterix (type modification) is part of a declarator. Actually declaration is formed of following ie.:

int i = 1, *pi = &i; 
^^^ ^^^^^^^^^^^^^^^ -- list of declarators 
 `- base type   

in above i is an int, whie pi is a pointer

in:

int* p1, p2; // p1 is a pointer, while p2 is an int
int *p1, p2; // same as above
marcinj
  • 48,511
  • 9
  • 79
  • 100