if/else and if/elseif

17,316

Solution 1

Situation a:

if( condition )
{
}
else
{
}

When the condition in the above statement is false, then the statements in the else block will always be executed.

Situation b:

if( condition )
{
}
else if( condition2 )
{
}
else
{
}

When 'condition' is false, then the statements in the else if block will only be executed when condition2 is true. The statements in the else block will be executed when condition2 is false.

Solution 2

Without "elseif" syntax you would have to write chain if-statements for processing one of several possible outcomes this way:

if( str == "string1" ) {
   //handle first case
} else {
    if( str == "string2" ) {
       //handle second case
    } else {
       if( str == "string3" ) {
           //handle third case
       } else {
          //default case
       }
    }
 }

instead you can write

if( str == "string1" ) {
   //handle first case
} else if( str == "string2" ) {
   //handle second case
} else if( str == "string3" ) {
   //handle third case
} else {
   //default case
}

which is completely the same as the previous one, but looks much nicer and is much easier to read.

Solution 3

Emphasizing what Gumbo said.

Also, if a language has a real elif / elsif / elseif (say, a "real" else-if instruction, instead of a kind of nested chaining hidden away by formatting), then the compiler can easly emit a single node in an Abstract Syntax Tree (or similar, see http://en.wikipedia.org/wiki/Abstract_syntax_tree) instead of nesting them.

To give an example:

Say in C/C++ you have:

if (a) {
    X
} else if (b) {
    Y
} else if (c) {
    Z
} else {
    0
}

Then the compiler will build an AST-node like this:

   a
  / \
 X   b
    / \
   Y   c
      / \
     Z   0

But if the language of choice has a real if-else:

if (a) {
    X
} elif (b) {
    Y
} elif (c) {
    Z
} else {
    0
}

Then the AST could more easily look like this:

   (a--b--c)
   /  /  /  \
  X  Y  Z    0

In such a language, an "if else" would only be possible if braces are not mandatory:

if (a) {
    X
} elif (b) {
    Y
} else if (c) {  // syntax error "missing braces" if braces mandatory
    Z
} else {
    0
}

Corresponding AST (if braces are not mandatory):

   (a--b)
   /  /  \
  X  Y    c
         / \
        Z   0

This could make CFG-Analysis (http://en.wikipedia.org/wiki/Control_flow_graph) easier to implement (though there might be no actual optimization benefit; so imho it'd just benefit the lazy programmer :D).

Solution 4

Many languages have a grammer like this (here: ECMAScript Language Specification, so JavaScript):

IfStatement :
    if ( Expression ) Statement else Statement
    if ( Expression ) Statement

Statement :
    Block
    VariableStatement
    EmptyStatement
    ExpressionStatement
    IfStatement
    IterationStatement
    ContinueStatement
    BreakStatement
    ReturnStatement
    WithStatement
    LabelledStatement
    SwitchStatement
    ThrowStatement
    TryStatement

Block :
    { StatementListopt }

StatementList :
    Statement
    StatementList Statement

So the branches of an ifStatement may contain a block of statements (Block) or one of the other statements (other than Block). That means this is valid:

if (expr)
    someStatement;
else
    otherStatement;

And as StatementList may just contain a single statement, these examples are equivalent to the previous:

if (expr) {
    someStatement;
} else {
    otherStatement;
}

if (expr)
    someStatement;
else {
    otherStatement;
}

if (expr) {
    someStatement;
} else
    otherStatement;

And when we replace otherStatement by an additional IfStatement, we get this:

if (expr) {
    someStatement;
} else
    if (expr) {
        someOtherStatement;
    }

The rest is just code formatting:

if (expr) {
    someStatement;
} else if (expr) {
    someOtherStatement;
}

Solution 5

else if basically means the else part of if is another if statement.

Share:
17,316

Related videos on Youtube

sharptooth
Author by

sharptooth

Updated on April 17, 2022

Comments

  • sharptooth
    sharptooth about 2 years

    If I have a statement block like this:

    if (/*condition here*/){ }
    else{ }
    

    or like this:

    if (/*condition here*/)
    else if (/*condition here*/) {}
    else if (/*condition here*/) {}
    

    What is the difference?

    It seems that with if/else, if part is for true state and the else part is for all other possible options (false). An else-if would be useful for a number of conditions. This is my understanding, is there anything more I should be aware of?

  • Romias
    Romias about 15 years
    The second case... the elseif one... is just like a Switch Case
  • sharptooth
    sharptooth about 15 years
    Exactly, but it is widely used and switch statement cannot be used for strings.
  • Peter Ajtai
    Peter Ajtai almost 14 years
    @sharpooth - They can in PHP and others I'm sure.
  • greenoldman
    greenoldman over 9 years
    No true, because with such syntax else if is side-effect (i.e. it comes for free). In other words there is no else if syntax, there is only if and else here.
  • sharptooth
    sharptooth over 9 years
    @greenoldman: Yes, you're right that it comes for free, however it is hardly a "side-effect" in language Standard terms, it's just a way of organizing code.
  • greenoldman
    greenoldman over 9 years
    @sharptooth, I meant it is side-effect, because if you design "if-else" in C-style, you will get else if and you don't have to make any change to syntax, correct? Compare this to Ruby/Perl/Python etc (the languages with blocks), and you have add new rules to syntax (unless you don't mind increased nesting).
  • sharptooth
    sharptooth over 9 years
    @greenoldman: Sure, except C++ Standard (1.9/7 in C++03) defines side-effects as changes in the state of the execution environment and the if-else-if chain behaves the same no matter how you indent it.