The if Statement


Syntax

if (expression)
 statement
 
if (expression)
 statement
else
 statement

Notes

Examples

Consider the following example:

if (a == b)
 if (c == d)
  e = f;
 else
  g = h;

The indenting correctly implies that the else applies to the latter rather than former if statement. That is, h is assigned to g only when a==b and c!=d.

If statements are often chained together as shown below.

if (a == b)
 i = 1;
else if (c == d)
 j = 2;
else if (e == f)
 k = 3;
else
 l = 4;

Multiple statements may be blocked together to form a single statement using braces, as shown below.

if (a == b)
 {
  i = 1;
  j = 2;
 }
else
 {
  k = 3;
  l = 4;
 }

Each of the two blocks enclosed by braces is treated as a single statement with respect to the syntax of the if - else statement.