switch statement in cplus plus


The switch construct


The switch statement is very similar to the if-else-if ladder of section statements. Here is its general form:

switch (expression)
{
case constant_1:
statement_1 or block_1;
break;
case constant_2:
statement_2 or block_2;
break;
case constant_3:
statement_3 or block_3;
break;
// More cases may follow
default
statement_X or block_X;
}

In the switch construct, as in the if-else-if construct, multiple possible blocks of code are being selected from, and only one of them will typically be executed. The presence of the keyword break allows the execution to come out of the switch statement. Omission of break takes control through the next case statements irrespective of whether the value of case matches or not. This can also be used constructively when same operation has to be performed on a number of cases.
Each case or possible block of code is initiated by the appearance of the case reserved word, and is terminated by the appearance of the break reserved word. The break is not required, but is almost always used.
The if-else-if and the switch structures have very similar usage in a program, but there are distinct differences. These differences are presented in the following table.

If-else construct
Switch construct
An expression is evaluated and the code is selected based on the truth value of the expression.
An expression is evaluated and the code is selected based on the value of the expression.
Each if has its own logical expression to be evaluated as true or false.
Each case is referring back to the original value of the expression in the switch statement.
The variables in the expression may evaluate to a value of any type, either an int or a char.
The expression must evaluate to an int.
Table shows Differences between if-else construct and switch construct
There is no subtle but very important difference between the if-else-if ladder and the switch statement. That difference involves the break statement. In the if-else-if ladder, no matter what, only one of the blocks of code is executed. In the switch construct, if the break statement in omitted, the flow of execution will go forward into the next block. The application of switch statement in performing arithmetic operations is shown in the following code segment:
float a,b;
char operation;
//Enter a number, an operation, and a number
switch (operation)
{
Case’+’:a + b;
Break;
Case’-’:a - b;
Break;
Case’*’:a * b;
Break;
Case’/’:a /b;
Break;
}

Based on the operation specified, the particular case is executed.

Flow-chart of switch statement


Comments

Popular posts from this blog

Rumors of women’s hair cutting in India

President of India

Php Tutorial