0

Say you have this..

 int fry = 50;

Now wen making a pointer and referencing the value, the asterisk can be placed two different ways:

 int* d1 = &fry;

and...

 int *d1 = &fry;

I was wondering what the difference is and what situation it would be best to use each? Thanks!

Road Rash
  • 131
  • 3
  • 14
  • 2
    There isn't really a difference. But it doesn't mean some people won't argue on how many angels you can fit on the head of pin. – Duck Nov 11 '13 at 01:18
  • purely style. The only place it matters is when using `const int* const name` – Serdalis Nov 11 '13 at 01:18
  • Duplicate of http://stackoverflow.com/questions/180401/pointer-declarations-in-c-placement-of-the-asterisk and many more. – s.bandara Nov 11 '13 at 01:23

2 Answers2

4

There is no difference. You can even do int*d1 and int * d1.

In my opinion, you should prefer int *d1: this choice has particular utility in avoiding confusion:

int* d1, d2;
int *d1, d2;

These statements both declare one integer and one pointer-to-integer. The first version looks quite misleading.

  • 1
    Best answer. It's important to keep in mind that the `*` is attached to the variable and not the data type. – nhgrif Nov 11 '13 at 01:21
2

There isn't a difference in the two examples that you give. As to which you should use, follow the style of the code you're working in.

Note, though, that the * binds to the variable, not they type. Thus,

int *this_is_a_pointer, this_is_just_an_int;

and

int* this_is_a_pointer, this_is_just_an_int;

are the same. If you had need for something like this, I'd actually write either of the following to avoid any confusion

int* this_is_a_pointer;
int this_is_just_an_int;

or

int *this_is_a_pointer;
int this_is_just_an_int;

depending on the style that is being used.

chwarr
  • 6,777
  • 1
  • 30
  • 57