-1

Possible Duplicate:
In C, what is the correct syntax for declaring pointers?

When I read C code, I see several ways to write a pointer,like

int *p;
char * s;
char * d = &c;
ll_model* model = new_ll_model(n, cc->term); 
double* avg_ll;

My questions are:

  1. Are there any differences between them?

  2. If there are, what are the differences? That is, does the position of white space and the * mean something?

  3. Which way is the right way to write a pointer, so it is readable to myself and any other person who will read my code

Community
  • 1
  • 1
Sean
  • 1,161
  • 1
  • 13
  • 24

4 Answers4

3

Functionally, no. You can read:

int *p;

as "the thing pointed to by p is an int" and

double* avg_ll

as "the type of avg_ll is pointer to double." AFAIK, the former is preferred C style and the latter is more prevalent in C++ code.

However, as the C FAQ explains, the latter style can lead to mistakes if you are in the habit of declaring multiple variables in a single statement.

Sinan Ünür
  • 116,958
  • 15
  • 196
  • 339
2

Basically, there's no difference between them.

But I prefer this method:

int *p;

Instead of:

int* p;

or

int * p;

The reason is that because if you want to declare a number of int * in the same line, it makes more sense to have the * next to the identifier instead of the type because that looks cleaner and less confusing. e.g.

int *p, *q, *r;

is better than:

int* p, *q, * r;

If you don't like my reasons, make sure you stick to one of them and don't vary the usage.

mmtauqir
  • 8,499
  • 9
  • 34
  • 42
0

There are plenty of differences between the lines of code you posted, but none of them are terribly relevant to how you declare a pointer type.

Whitespace does not matter.

What is readable is in the eye of the beholder. I prefer placing a single space character before and after the * character(s).

Michael Price
  • 8,088
  • 1
  • 17
  • 24
0

Answers

  1. Yes they are different types of pointer because of different types
  2. The white space makes no difference - the difference is used in pointer arithmetic. If you increment a char * it move the pointer on by 1 char. If you increment a int * it moves on the pointer by the size of 1 int
  3. I prefer char *foo style - but my style is a little old by now
Adrian Cornish
  • 23,227
  • 13
  • 61
  • 77