views:

115

answers:

6

Possible Duplicate:
What’s your preferred pointer declaration style, and why?

I know that technically all three ways below are valid, but is there any logical reason to do it one way or the other? I mean, lots of things in c++ are "technically valid" but that doesn't make them any less foolish.

int* someFunction(int* input)
{
    // code
}  

or

int *someFunction(int *input)
{
    // code
}

or

int * someFunction(int * input)
{
    // code
}

I personally think the third one is annoying, but is there a "correct" way? I am typically more inclined to use the first one (as the second looks more like it's being used as the dereference operator - which it isn't)

+1  A: 

All are equivalent. Choose the flavor that suits you best. Just be sure whichever you chose, you apply that choice in every case. Where your stars and curly braces go is far less important than putting them in the same place every time.

Personally, I prefer int* someFunction(int* input);, but who cares?

John Dibling
I figured that would be the general consensus, but I feel like whoever originally came up with it probably intended for it to be one particular way... I'm just curious which one.
advs89
Matthew Flaschen
Stroustrup says that C++ programmers often use the first. I have been known to use the third. Go figure. http://www2.research.att.com/~bs/bs_faq2.html
John Dibling
advs89
A: 

I prefer the second, for the reasons explained in my previous answer. *someFunction(someInput) has type int.

EDIT: Kernigan and Ritchie definitely intended the second. See for instance this snippet from the white bible.

Matthew Flaschen
A: 

There's no "one correct way". It is all a matter of personal preference.

The first approach is not generally compatible with having multiple declarators in one declaration, so people who use it usually don't use more than one declarator in a declaration

int* p, b; // misleading, since `b` is `int` and not `int*`

Yet the first approach has its supporters.

AndreyT
A: 

It's a question of personal taste. I prefer the 1st approach, whereas the old-school programmers tend to use the 2nd (coming from the old good C times).

For a difference, consider the following:

int* p, q; // here p is a pointer to int, but q is just an int!

The attractiveness of the first way (int* p) is that it reads as "int pointer is a type of p", whereas the alternate int *p reads as "int is a type of *p" (which is also correct).

Vlad
A: 

I personally use the second option, because int *p1, p2; is better looking and less confusing than int* p1, p2; or int * p1, p2;. The same with functions' return type to keep the same style.

It's a personal thing, there isn't any 'good' or 'bad' way.

MeDiCS
A: 

All are equivalent. I like the third because it makes the * stand out. Other people differ.

If you're working on a project with others, use the established style. If not, decide on your own style.

David Thornley