Else If Clause – Specific Reasons to Use It in Programming

algorithmsprogramming-languages

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?

Best Answer

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).

Related Topic