Wednesday, 3 December 2014

Switch statement..........


C has a built-in multiple-branch selection statement, called switch, which successively tests the
value of an expression against a list of integer or character constants. When a match is found, the
statements associated with that constant are executed. The general form of the switch statement is

switch (expression) {
case constant1:
statement sequence
break;
case constant2:
statement sequence
break;
case constant3:
statement sequence
break;
.
.
.
default
statement sequence
}
The expression must evaluate to an integer type. Thus, you can use character or integer values, but
floating-point expressions, for example, are not allowed. The value of expression is tested against
the values, one after another, of the constants specified in the case statements. When a match is
found, the statement sequence associated with that case is executed until the break statement or the
end of the switch statement is reached. The default statement is executed if no matches are found.
The default is optional, and if it is not present, no action takes place if all matches fail.
C89 specifies that a switch can have at least 257 case statements. C99 requires that at least 1,023
case statements be supported. In practice, you will usually want to limit the number of case
statements to a smaller amount for efficiency. Although case is a label statement, it cannot exist by
itself, outside of a switch.
The break statement is one of C's jump statements. You can use it in loops as well as in the switch
statement (see the section ''Iteration Statements"). When break is encountered in a switch, program
execution "jumps" to the line of code following the switch statement.
There are three important things to know about the switch statement:
• The switch differs from the if in that switch can only test for equality, whereas if can evaluate any
type of relational or logical expression.
• No two case constants in the same switch can have identical values. Of course, a switch statement
enclosed by an outer switch may have case constants that are in common.
• If character constants are used in the switch statement, they are automatically converted to integers
(as is specified by C's type conversion rules).

No comments:

Post a Comment