1

We all use if ..else if.. else.

But still I'm confused as to why we use else if. Where if does the same thing as else if.

So why are we using else if?

Any specific reasons behind this?

Is there any algorithm where it's mandatory to use else if?

  • 1
    You could actually ask why use else at all (not just the else if combo). After all, one can always write if (a) ... if (!a) instead. Well, it's just more expressive. – Konrad Morawski Jan 10 '14 at 14:48
  • 1
    PLUS if (a) doSomething else doSomethingElse ensures that if doSomething was executed, doSomethingElse won't. if (a) doSomething; if (!a) doSomethingElse makes it possible (if a was true before doSomething, but doSomething changed its value to false). – Konrad Morawski Jan 10 '14 at 14:54
  • Why, it's nothing special? You could also ask "Is there a specific reason we use else while, else return, else assignment, ..." – Ingo Jan 10 '14 at 18:17
  • It is used to denote multiple branching targets when all of the conditions are mutually exclusive (disjoint). In some languages, switch case have been extended to handle mutually exclusive branching thus making else if optional. In C and C++, this is not the case because of historical reasons. – rwong Jan 10 '14 at 20:25
22

The main reason to use else if is to avoid excessive indentation.

For example:

    if(a) {
    } else {
        if(b) {
        } else {
            if(c) {
            } else {
            }
        }
    }

Can become:

    if(a) {
    } else if(b) {
    } else if(c) {
    }

Of course both of the pieces of code above are equivalent (which means it's impossible for the latter to be mandatory other than in style guides).

  • 4
    Another option would be: if(a) { } if(!a && b) {} if(!a && !b && c) {} Just imagine this madness for more and bigger conditions. – Flo Jan 10 '14 at 8:02
  • 18
    @RanjitPati: Side note: There is no such thing as an "else if". It does not exist in the language grammar. "else" goes down the next statement if the if statement is false, and an if statement is a statement. Essentially, the answer to this question is "You are using an if statement already". – Phoshi Jan 10 '14 at 9:41
  • 1
    if..else if.. is a very bad code smell. It is often a source of error and even where there is no error it is usually a sign of poor code structure. – itsbruce Jan 10 '14 at 10:50
  • 2
    @Phoshi Which is interesting to note, because it means constructs like if (bool) { ... } else try { ... } catch { ... } are entirely valid. It's probably not advisable, because most people aren't used to seeing it written that way, but the same principle applies. – KChaloux Jan 10 '14 at 13:41
  • 2
    @itsbruce: That’s hilarious—please tell me you’re not serious! – Jon Purdy Jan 11 '14 at 0:32
6

the question asks, "why do you need else given that you can accomplish the same functionality using only if" (paraphrased). First of all, the two are only really equivalent in fairly simple programs; there are many situations where else if functionality cannot be easily replicated using only if statements.

that said, in such simple situations it is still usually better to use else if.

if (a==b){}
if (!(a==b) && a==c ){}

there are two problems with this that are solved by using else if. First, you perform the comparison between a and b twice, which is unnecessary work. Second, unless you memorize the rules or rely heavily on parenthesis, it's not obvious how the second boolean expression resolves.

if (a==b) {}
else if (a==c) {}

Is cleaner, clearer, and more efficient. It's basically the programming holy grail.

  • You do understand there is a difference between those two statements right? In your first example both statements will always be checked. In the second the second will only be checked if the first one is false. This difference is the reason for the downvote. To make the first one equal place the if statement within an else statement. – Ramhound Jan 10 '14 at 13:54
  • There's a semantic difference as well. If a or b, or c changes within the first block (if (a==b)), both blocks may get executed. if - else if is insensitive to that. As for "unnecessary work" - this sort of performance hit is typically irrelevant, unless eg. a and b are methods that take long to evaluate. It's also a rather poor sign if a programmer hasn't memorized the rules required to understand how (!(a==b) && a==c ) evaluates. – Konrad Morawski Jan 10 '14 at 14:43
  • For more complicated expressions, as might arise from attempting to chain this along for any significant length, the boolean expression can become substantially unclear...particularly if some of the previous ifs used a complicated predicate itself -- (!(a&b==c) && (c >d || d==5) && ((a*d > g) && !(a > 12))...) might be easily parsed into sub expressions, but certainly isn't clear – colinro Jan 10 '14 at 21:57
3

It's for efficiency. If you have a chain of if...else if...else if clauses, then evaluation stops after one evaluates to true. If you simply have a list of if clauses, then even after one evaluates to true, you'll still check the rest of them, even though they'll be false. If the conditions involve invoking functions or other "expensive" operations then you'll waste resources (especially if your conditions involve web service calls or database lookups). This is also why you should try to structure complicated conditional expressions like this so that the "cheapest" conditions are checked first.

2

If we think programmatically the main purpose is if we have to choose one thing among many things at that time we should use else if.

Also there can be many ways of doing same things like switch..case in that case we can consider it as another construct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.