C Syntax - Control Structures - Selection Statements

Selection Statements

C has two types of selection statements: the if statement and the switch statement.

The if statement is in the form:

if () else

In the if statement, if the in parentheses is nonzero (true), control passes to . If the else clause is present and the is zero (false), control will pass to . The else part is optional and, if absent, a false will simply result in skipping over the . An else always matches the nearest previous unmatched if; braces may be used to override this when necessary, or for clarity.

The switch statement causes control to be transferred to one of several statements depending on the value of an expression, which must have integral type. The substatement controlled by a switch is typically compound. Any statement within the substatement may be labeled with one or more case labels, which consist of the keyword case followed by a constant expression and then a colon (:). The syntax is as follows:

switch () { case : case : break; default : }

No two of the case constants associated with the same switch may have the same value. There may be at most one default label associated with a switch. If none of the case labels are equal to the expression in the parentheses following switch, control passes to the default label or, if there is no default label, execution resumes just beyond the entire construct.

Switches may be nested; a case or default label is associated with the innermost switch that contains it. Switch statements can "fall through", that is, when one case section has completed its execution, statements will continue to be executed downward until a break; statement is encountered. Fall-through is useful in some circumstances, but is usually not desired. In the preceding example, if is reached, the statements are executed and nothing more inside the braces. However if is reached, both and are executed since there is no break to separate the two case statements.

It is possible, although unusual, to insert the switch labels into the sub-blocks of other control structures. Examples of this include Duff's device and Simon Tatham's implementation of coroutines in Putty.

Read more about this topic:  C Syntax, Control Structures

Famous quotes containing the words selection and/or statements:

    When you consider the radiance, that it does not withhold
    itself but pours its abundance without selection into every
    nook and cranny
    Archie Randolph Ammons (b. 1926)

    We assume that politicians are without honor. We read their statements trying to crack the code. The scandals of their politics: not so much that men in high places lie, only that they do so with such indifference, so endlessly, still expecting to be believed. We are accustomed to the contempt inherent in the political lie.
    Adrienne Rich (b. 1929)