Society & Lifestyle
|Computing||Share This Page|
Decision Making And Branching
|by Sachin Mehta|
We continue with the remaining decision making statement, switch, conditional operator & the GOTO statement.
The Switch Statement
We have seen that when of many alternatives is to be selected, we can use the if statement. In all cases programs can be designed using only this statement. However, the complexity of such a program increases dramatically when the number of choices increases. The clarity of the program decreases. 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. value1, value2, .... are constants or constant expressions and are known as case labels. Each of these values should be unique within a switch statement. block1, block2,...... are statement lists and may contain zero or more statements. There is no need to put braces around these blocks. Note that case labels end with a colon .
The value of variable n is accepted and then tested using the switch statement. Any value other than 1 or 2 will lead to end of the default block.
The ? : Operator
This operator is popularly known as the conditional operator. The general form of the conditional operator is as follows:
In all the statements seen one common thing was that, there execution depended on some condition. However we also have statements in which are unconditional. Like many other languages, C supports the GOTO statement to branch unconditionally from one point to another in the program. Although it may not be essential to use the GOTO statement in a highly structured language like C, there may be occasions when the use of GOTO might be desirable.
The GOTO requires a label in order to identify the place where the branch is to be made. A 'label' is placed immediately before the statement where the control is to be transferred. The general forms of GOTO and label statements are shown below:
GOTO label; label: statement;
This label can sometime generate infinite loops which should be avoided. The labels used for GOTO statement do not require any kind of declaration as necessary in PASCAL.
|More by : Sachin Mehta|
|Views: 2892 Comments: 1|
Comments on this Article
10/02/2013 01:30 AM
|Top | Computing|