Using <I>else</I>


Of course, if you have an if, you've got to be able to have an else. C++ handles this else like Pascal does, with one critical difference. Try and find it in the example!

void main(void)
{
  double a;
 
  a = 0.5;  /*  Not 0, so it's TRUE! */

  if (a)
    a = 10000;
  else
    a = 10;
}

You may have missed it. Take a look at the statement "a = 10000;". Note that, even though an else comes right after it, it has a semicolon! This is due to a fundamental difference between how semicolons work in C++ versus Pascal. In Pascal, the semicolon was a separator, while in C++, the semicolon is a terminator. This means that in Pascal, you have:

(statement) ; (statement) ; (statement)

Notice how the semicolons are just acting as a boundary between where one statement ends and one statement begins. However, in C++, you have:

(statement) ; (statement) ; (statement) ;

Look at how there's a semicolon after each statement. Because the semicolon terminates each statement, it must be placed at the end of every single statement. For this reason, even though else comes after the if statement, you still have to use the semicolon.

This has a little to do with why there's no "then" in an if statement anymore; since we've removed it from the if statement, C++ uses the parentheses to determine exactly where the if statement ends and the lines it should execute begin.


Table of Contents

The Big Picture | Comments | Variables | More on Variables
Variable Operations | Making Choices | More on if | Using else
Using switch | The while Loop | The do..while Loop | Constants
The for Loop | More on the for Loop | Exercises