Coding Guidelines: Parameter order

I have two suggestions here, one is the order:

void func (int a, int b, int& result);
void func (int& result, int a, int b);

I prefer the former, since nominally you have input -> output, and not output -> input (at least in a LTR language :).

But I'd like to take it a step further and propose this format for functions with output variables:

void func (int a, int b, int* result);

Rationale: Having the output variable as a pointer makes the code more readable at the call site:

int result;

func(a, b, &result);

That makes it obvious directly at the calling site, which parameters are outputs.




Is there a reason why you use in/out parameters (via references or pointers, doesn't matter) instead of simply returning the result? My personal coding guideline is simply: avoid in/out parameters whenever you can. For almost all usecases, there are better and more modern C++ alternatives.

That being said, If I had to pick one of your options, I'd go with

void func (int a, int b, int& result);

Having the result at the end feels more logical, and using a non-const reference feels more C++ like (dealing with pointers and address-of-operators feels C'ish and is another thing I try to avoid whenever I can ;-) and also references are guaranteed to be non-null, whereas pointers aren't - this is important in this case as it saves you a check)

Regarding the order I usually take the opposite, because I might have default arguments as input variables. It makes no sense to omit the output, therefore I have the output before the input arguments.

Just my 2ct.

I'm with Daniel. Not only is it handy having the option to set default arguments open, I find designing this approach makes the output parameter consistent and predictable (and non-negotiable, unlike pointers would do. Sorry Robiwan!).

Also, while writing out these types of functions, I find that it's easier to edit with the output parameter first. Spares me from reformatting, or reformatting often!

Thank you, good points all, although some would argue that default parameters is a "bad thing" :) and should be handled by different methods instead, at which point the out before in argument becomes moot, but I digress ;)

Besides, Timur has a point, at least now with C++11 we can use std::tuple<> for returning multiple results, which unless it is required that passed output parameter is externally defined, is a better choice overall.

The pointer style method prototype was used by a company I worked for, and it was a handy way of seeing directly if a parameter was an output or not, so I got used to it quicly :) But I agree, it is not very C++-ish.