9

I am fairly new at C and I don't know the difference between the following two variable declarations:

int* ptr;
int *ptr;

I think that in the declaration int* ptr;, ptr's value cannot be changed whereas it can be changed for the declaration, int *ptr;

I am not sure if that is it though.

What is the concept behind the two declarations?

halfer
  • 19,824
  • 17
  • 99
  • 186
anpatel
  • 1,952
  • 4
  • 19
  • 36
  • possible duplicate of [C: is there a difference between "int\* fooBar;" and "int \*fooBar;"?](http://stackoverflow.com/questions/2093459/c-is-there-a-difference-between-int-foobar-and-int-foobar) and [Difference between int \*i and int\* i](http://stackoverflow.com/questions/3770187/difference-between-int-i-and-int-i), [Difference between int\* p and int \*p declaration](http://stackoverflow.com/questions/5590150/difference-between-int-p-and-int-p-declaration) along with at least a dozen others. – jscs Oct 17 '11 at 21:08
  • http://stackoverflow.com/questions/3770187/difference-between-int-i-and-int-i – Pi Delport Oct 17 '11 at 21:11

5 Answers5

26

To the compiler, there is no difference between the two declarations.

To the human reader, the former may imply that the "int*" type applies to all declarations in the same statement. However, the * binds only to the following identifier.

For example, both of the following statements declare only one pointer.

int* ptr, foo, bar;
int *ptr, foo, bar;

This statement declares multiple pointers, which prevents using the "int*" spacing.

int *ptr1, *ptr2, *ptr3;
Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
4

Spaces in C are mostly insignificant. There are occasional cases where spaces are important, but these are few and far between. The two examples you posted are equivalent.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
2

Like the others said. There is no difference. If you want to understand more complex C type declaration you could find this link userful. Reading C declarations.

Xyand
  • 4,470
  • 4
  • 36
  • 63
1

It's called whitespace operator overloading, see here: http://www2.research.att.com/~bs/whitespace98.pdf

Dabbler
  • 9,733
  • 5
  • 41
  • 64
1

int *p;

*p 


is no meaning for compiler, (int*) is a type named pointer.

Mustafa Ekici
  • 7,263
  • 9
  • 55
  • 75