The switch Statement:



As we know that when one of the many alternatives is to be selected, we can use an if statement to control the selection. However, the complexity of such a program increases dramatically when the number of alternative increases. The program becomes difficult to read and follow. At times, it may confuse even the person who designed it. Fortunately, C has a built – in – multiway decision statement known as a switch. The switch statement tests the value of a given variable ( or expression) against a list of case values and when a match is found, a block of statements associated with that case is executed. The general form of the switch statement is as shown below:


The expression is an integer expression or characters. Value -1, value -2….. are constants and are known as case labels. Each of these values should be unique within a switch statement. block -1, block -2…… are statement lists and may contain zero or more statements. There is no need to place braces around these blocks. Note that case labels end with a colon (:).

When the switch is executed, the value of the expression is successfully compared against the values value – 1, value -2,… If a case is found whose value matches with the value of the expression, then the block of statements that follow the case are executed.

The break statement at the end of each block signal the end of a particular case and causes an exit from the switch statement, transferring the control to the statement – x following the switch.

The default is an optional case. When present, it will be executed if the value of the expression does not match with any of the case values. If not present, no action takes place if all matches fails and the control goes to the statement –x.
The selection process of switch statement is in the flowchart as shown below:




Previous                                                                                    Next


Powered by Blogger.