views:

791

answers:

7

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?

+2  A: 

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

Mehrdad Afshari
A: 

Given a single variable, you will use the simple if-else structure. When there are multiple variables and you have a different path to execute for the different possibilities, you will use if-else if-...-else. Note, that the latter also ends with an else statement.

dirkgently
+11  A: 

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.

Frederik Gheysels
+18  A: 

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.

sharptooth
The second case... the elseif one... is just like a Switch Case
Romias
Exactly, but it is widely used and switch statement cannot be used for strings.
sharptooth
@sharpooth - They can in PHP and others I'm sure.
Peter Ajtai
A: 

You already gave the answer yourself. if/else is for true/false result, like is an int=2 or any other possible int value, and if/elseif is for more than 2 results, like an int=2, and int=3 and so on.

Also it groups the context of a variable. You could check every single result like

if (a == 2) { do one thing };
if (a == 3) { do another thing };
...
if (a != 2 && a != 3 ...) { do something else };

With if/else/elseif it's better readable.

DaClown
+2  A: 

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;
}
Gumbo
+3  A: 

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

phresnel