If … else …

The 'if … else …' statement causes the interpreter to choose between one or two alternative statements and execute at most one set. The syntax is:

if ( condition )
    statement or block

or

if ( condition )
    statement or block
else
    statement or block

In the first form, if the condition is met, then the statement or block of statements is done, otherwise it is skipped. In the second form, if the condition is met, then the first statement or block is done, otherwise the second one is. Each possible block is called a branch. Since a block has parentheses, but a statement doesn't, it follows that parentheses are optional if there is only one statement in a branch. Some examples:

if ( x == 5 )         // first example
    y = 6;

if ( name == "fred")      // second example
    y = 6;
else
    y = 7;

if ( x == y && a == b )      // third example
{
     x++;
     y++;
}
else
{
    a++;
    b++;
}

The statements making up each branch are indented only for ease of reading. Like HTML, it makes no difference to the result if there's extra whitespace included.

© 1997 by Wrox Press. All rights reserved.