问题
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:
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?
回答2:
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).
回答3:
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.
回答4:
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.
回答5:
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.
回答6:
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.
来源:https://stackoverflow.com/questions/2367202/c-pointer-in-function