Cpp - else if Chains

Introduction

You can use an else-if chain to execute one of several options.

if-else statements layout is normally as follows:

if ( expression1 ) 
    statement1 
else if( expression2 ) 
    statement2 
          . 
          . 
          . 
else if( expression(n) ) 
    statement(n) 
 [ else statement(n+1)]  

When the else-if chain is executed, expression1, expression2, ... are evaluated in the order in which they occur.

If one of the expressions proves to be true, the corresponding statement is executed and this terminates the else-if chain.

If none of the expressions are true, the else branch of the last if statement is executed.

If this else branch is omitted, the program executes the statement following the else-if chain.

Demo

#include <iostream> 
using namespace std; 

int main() /* w  w w . j  a va  2 s.  c o  m*/
{ 
    float limit, speed, toofast; 
    cout << "\nSpeed limit: "; 
    cin >> limit; 
    cout << "\nSpeed: "; 
    cin >> speed; 

    if( (toofast = speed - limit ) < 10) 
       cout << "You were lucky!" << endl; 
    else if( toofast < 20) 
       cout << "Fine payable: 40,-. Dollars" << endl; 
    else if( toofast < 30) 
       cout << "Fine payable: 80,-. Dollars" << endl; 
    else 
       cout << "Hand over your driver's license!" << endl; 
    return 0; 
}

Result

Related Topic