The if Statement


The if statement has the following form.

if (condition)
 statement;
else
 statement;

The condition must be a boolean expression (i.e. produces a bool). When the boolean expression evaluates to true, the if statement is executed; otherwise, the else statement is executed. The target statements of the if and else portions are single statements. The else portion is optional. The general form when using blocks for multiple statements is as follows.

if (condition)
 {
  statement sequence
 }
else
 {
  statement sequence
 }

A common programming construct using if is shown below.

if (condition)
 statement;
else if (condition)
 statement;
else if (condition)
 statement;
....
else
 statement;

The conditions are evaluated in order from top to bottom. When a condition is found to be true, the corresponding statement is excecuted and the remainder of the statement is bypassed. If none of the conditions evaluates to true, the else portion is executed. Thus, one and only one of the consequent statements will be executed. A switch statement is often used in similar circumstances, but a switch statement is more specific. The above logic can include very general and varied conditions.