I can tell you which one I would use, and for which reasons, however I think there will be as many opinions as community members here...
1) Neither. I would write:
long int multiplyNumbers(int n)
{
if (n < 1) {
return 1;
}
return n*multiplyNumbers(n-1);
}
This is because I like the idea of "early exit" in the special cases, and this reminds me of that scenario. The general rule is: if you need to handle a special case or a general case, handle the special case first. Presumably the special case (e.g. error or a boundary condition) will be handled quickly and the rest of the code is still not too far from the 'if' condition so that you cannot skip a few lines of code to look into it. It also makes reading the general case handling easier, because you need to just scroll down the function body.
In other words, instead of:
void foo(int bar)
{
if (!special_case_1) {
if (!special_case_2) {
return handle_general_case();
}
else {
return handle_special_case_2();
}
}
else {
return handle_special_case_1();
}
}
I am advocating writing this:
int foo(int bar)
{
if (special_case_1) {
return handle_special_case_1();
}
if (special_case_2) {
return handle_special_case_2();
}
return handle_general_case();
}
You will notice that, if it is feasible, I prefer not to introduce an additional variable 'result' here, mostly because then I don't need to care whether it is initialised or not. (If you introduce it, then either you initialise it at the top, only to be overwritten in each branch, or you don't, and then you may forget to initialise it in some branch. Plus, even if you initialise it in every branch, your static code analyser may not see this and may complain for no reason.)
2) I would use (b) (with declaration of 'result' thrown away). This is because in this case I cannot say that either num1 < num2 or num1 >= num2 is a special case. They are equal to my eyes and thus (b) is preferred over (c). (I've already explained why, in this case, I wouldn't introduce an additional variable, so (a) is in my eyes inferior to (b).)
if
statement contains areturn
, soelse
is redundant.int result
.return (num1 > num2) ? num1 : num2;
simplifies case 2 and shows that you're returning a value regardless of what the condition evaluates to.if
else
blocks are the better choice when you should perform different logic for each branch.