The if statement

An if statement is a selection statement that allows more than one possible flow of control.

C++ 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.

C 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.

Read syntax diagramSkip visual syntax diagramif statement syntax
 
>>-if--(--expression--)--statement--+-----------------+--------><
                                    '-else--statement-'
 

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.

A single statement following any selection statements (if, switch) is treated as a compound statement containing the original statement. As a result any variables declared on that statement will be out of scope after the if statement. For example:

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.



[ Top of Page | Previous Page | Next Page | Contents | Index ]