12

Possible Duplicate:
int* i; or int *i; or int * i;

Thinking about where we place our asterisks; how do those that prefer to keep the "pointerness" away from the type and with the identifier (int *i) write code when the identifier is missing?

void f(int*); // 1
void f(int *); // 2

The former seems much more common, no matter what your preference when with the identifier. Is this a special case? What makes it an exception?

However, the first still isn't universal, because I have seen the latter style. Besides consistency along the lines of "there's always a space with the identifier, so we have one without", are there any other reasons to prefer it?

What about casts or array and function types? How would you re-write these:

(void*)var /*or*/ (void *)var

int[3] /*or*/ int [3]
// more relevant in C++ than C: Example<int[3]>

void(int) /*or*/ void (int)
// more relevant in C++ than C: std::function<void(int)>

The latter two would rarely, if ever, be used in C, but are seen with C++ templates.

4 Answers4

16

The goal should be to make the code readable and clear. The style int* a; may seem fine, but when it becomes int* a, b; it implies something different than what it really is. Contrast with int *a, b; and int *a, *b; where each reads exactly like the way it works.

The difference between void f(int*); and void f(int *); for readability is negligible, and I can't find myself caring much which one is used.

When you remember the top level goal (readability) it's easier to separate pure nitpicks from potential comprehension/maintenance problems.

dwc
  • 2,006
6

I always separate the star from the type, so I use:

void f(int *);

void f(int *x)
{
    char *y = (char *) x;
    char x[4];
}

Obviously, I don't separate the brackets from the identifier.

That's how I learned to do it from K&R, and who am I to argue? (Also, it seems to be the most readable way.)

mipadi
  • 7,533
2

It is definitely NOT about style, or readability, or maintainability, or anything aesthetic.

The syntax of C, and therefore also C++, require it.

Here's an example:

int *a, *b, *c;

That makes three pointers.

However:

int* a, b, c;

That makes a pointer, and two ints.

doug65536
  • 198
1

Unless specifically instructed otherwise, I tend to follow the C paradigm for stuff like that; namely, T *, T [N], T (*)(), etc., whether I'm writing C or C++, because pointer-ness and array-ness and function-ness are all functions of the declarator, not the type specifier.

However, I will follow the common paradigm for the given language when declaring objects:

T* foo; // C++
T *bar; // C

Is this an inconsistency in my coding style? Yes. Is it a big deal? Not until someone complains about it.

John Bode
  • 11,004
  • 1
  • 33
  • 44