The if statement
An if statement is a selection statement that allows more than one possible flow of control.
An if statement lets you conditionally process a statement when the specified test expression, implicitly converted to bool, evaluates to true. If the implicit conversion to bool fails the program is ill-formed.
In C, an if statement lets you conditionally process a statement when the specified test expression evaluates to a nonzero value. The test expression must be of arithmetic or pointer type.
You can optionally specify an else clause on the if statement. If the test expression evaluates to false (or in C, a zero value) and an else clause exists, the statement associated with the else clause runs. If the test expression evaluates to true, the statement following the expression runs and the else clause is ignored.
When if statements are nested and else clauses are present, a given else is associated with the closest preceding if statement within the same block.
if (x)
int i;
is equivalent to: if (x)
{ int i; }
Variable i is visible only
within the if statement. The same rule applies to
the else part of the if statement.Examples of if statements
The following example causes grade to receive the value A if the value of score is greater than or equal to 90.
if (score >= 90)
grade = 'A';
The following example displays Number is positive if the value of number is greater than or equal to 0. If the value of number is less than 0, it displays Number is negative.
if (number >= 0)
printf("Number is positive\n");
else
printf("Number is negative\n");
The following example shows a nested if statement:
if (paygrade == 7)
if (level >= 0 && level <= 8)
salary *= 1.05;
else
salary *= 1.04;
else
salary *= 1.06;
cout << "salary is " << salary << endl;
The following example shows a nested if statement that does not have an else clause. Because an else clause always associates with the closest if statement, braces might be needed to force a particular else clause to associate with the correct if statement. In this example, omitting the braces would cause the else clause to associate with the nested if statement.
if (kegs > 0) {
if (furlongs > kegs)
fxph = furlongs/kegs;
}
else
fxph = 0;
The following example shows an if statement nested within an else clause. This example tests multiple conditions. The tests are made in order of their appearance. If one test evaluates to a nonzero value, a statement runs and the entire if statement ends.
if (value > 0)
++increase;
else if (value == 0)
++break_even;
else
++decrease;