The switch Case Statement in C

The switch Case Statement

The switch-case statement is used when an expression‘s value is to be checked against
several values. If a match takes place, the appropriate action is taken. The general
form of switch case statement is:
switch (expression)
case constant1 :
case constant2 :
In this construct, the expression whose value is being compared may be any valid
expression, including the value of a variable, an arithmetic expression, a logical
comparison rarely, a bit wise expression, or the return value from a function call, but
not a floating-point expression. The expression‘s value is checked against each of the
specified cases and when a match occurs, the statements following that case are
executed. When a break statement is encountered, control proceeds to the end of the
switch - case statement.

The break statements inside the switch statement are optional. If the break statement
is omitted, execution will continue on into the next case statements even though a
match has already taken place until either a break or the end of the switch is reached.

The keyword case may only be constants, they cannot be expressions. They may be
integers or characters, but not floating point numbers or character string.
Case constants may not be repeated within a switch statement.

The last case is a special keyword default. The default statement is execut ed if no
matches are found. The default is optional and if it is not present, no action takes place
if all matches fail.

Three important things to know about switch statement:
1. 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.
2. No two case constants in the same switch can have identical values. But, a
switch statement enclosed by an outer switch may have case constants and
either same.
3. If character constants are used in the switch statement, they are
automatically converted to integers.

Custom Search

%d bloggers like this: