Table of Contents
Previous Section Next Section

if

The if keyword allows a course of action to be based on the outcome of a condition. The general form of the if statement is

if(condition) {
    statement block 1
}
else {
    statement block 2
}

If single statements are used, the braces are not needed. The else is optional.

The condition may be any expression. If that expression evaluates to true (any value other than zero), then statement block 1 will be executed; otherwise, if it exists, statement block 2 will be executed.

The following fragment checks if x is greater than 10:

if(x > 10)
  cout << "x is greater than 10.";
else
  cout << "x is less than or equal to 10.";

Table of Contents
Previous Section Next Section