To contents Next section

3.1.1 if

The simplest one is called the if statement. It can be written anywhere where a statement is expected and it looks like this:
if( expression ) statement1; else statement2;
Please note that there is no semicolon after the parenthesis or after the else. Step by step, if does the following:
  1. First it evaluates expression.
  2. If the result was false go to point 5.
  3. Execute statement1.
  4. Jump to point 6.
  5. Execute statement2.
  6. Done.
This is actually more or less how the interpreter executes the if statement. In short, statement1 is executed if expression is true otherwise statement2 is executed. If you are interested in having something executed if the expression is false you can drop the whole else part like this:
if( expression )
    statement1;
If on the other hand you are not interested in evaluating something if the expression is false you should use the not operator to negate the true/false value of the expression. See chapter 5 for more information about the not operator. It would look like this:
if( ! expression )
    statement2 ;
Any of the statements here and in the rest of this chapter can also be a block of statements. A block is a list of statements, separated by semicolons and enclosed by brackets. Note that you should never put a semicolon after a block of statements. The example above would look like this;
if ( ! expression )
{
    statement;
    statement;
    statement;
}

To contents Next section