By Stephen R. Davis

C++ allows the program to specify a clause after the keyword else that is executed if the conditional expression is false, as in the following example:

if (m > n)   // if m is greater than n...
{
             // ...then do this stuff;...
}
else         // ...otherwise,...
{
             // ...do this stuff
}

The else clause must appear immediately after the close brace of the if clause. In use, the else appears as shown in the following snippet:

if (nAge < 0)
{
    cout << "Age can't be negative; using 0." << endl;
    nAge = 0;
}
else
{
    cout << "Age of " << nAge << " entered" << endl;
}

In this case, if nAge is less than zero, the program outputs the message “Age can’t be negative; using 0.” and then sets nAge to 0. This corresponds to the flow of control shown in the first image. If nAge is not less than zero, the program outputs the message “Age of x entered”, where x is the value of nAge. This is shown in the second image.

image0.jpg