15

When to use else in conditions?

1)

a)

long int multiplyNumbers(int n)
{
    if (n >= 1) {
        return n*multiplyNumbers(n-1);
    } else {
        return 1;
    }
}

or

b)

long int multiplyNumbers(int n)
{
    if (n >= 1) {
        return n*multiplyNumbers(n-1);
    } 

    return 1;
}

2)

a)

int max(int num1, int num2) {
   int result;

   if (num1 > num2) {
      result = num1;
   } else {
      result = num2;
   }

   return result; 
}

or

b)

int max(int num1, int num2) {

   if (num1 > num2) {
      return num1;
   } else {
      return num2;
   }
}

or

c)

int max(int num1, int num2) {
   if (num1 > num2) {
      return num1;
   } 

   return num2;
}

Is there a rule about when to use else?

Do the if with else statements take more memory? On the one hand, they are more readable, but on the other hand, too much nesting is poor reading.

If I throw exceptions, then it is better not to use else, but if these are ordinary conditional operations like in my examples?

zohub
  • 161
  • 3
  • C is fine, except that you never use int result.
  • – Robert Harvey Jan 19 '18 at 19:16
  • I find it confusing when I read a pointless else after a return. – Erik Eidt Jan 19 '18 at 19:25
  • @RobertHarvey sorry, int result in this example was mistake. Please add new answer. – zohub Jan 19 '18 at 19:27
  • 3
    About redundant elses after returns: It depends. In asynchronous or callbacky code, like node.js, it is fairly common to use both, as a "belt and suspenders" way to avoid bugs. As for this question, I'd probably use a ternary operator for all the case. – user949300 Jan 19 '18 at 19:30
  • 4
    I agree with @user949300, I'd use a ternary because you're peforming the same action for each case (returning a value). 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. – Wes Toleman Jan 20 '18 at 17:06
  • Something to be said for returning the most often expected result first in some languages. – Mark Schultheiss Jan 20 '18 at 18:50