C++ is one of the most versatile languages in the world. It is used nearly everywhere for everything… systems programming (operating systems, device drivers, database engines, embedded, Internet of Things, etc.)

Enter Header Image Headline Here

Saturday, 15 April 2017

C++ switch...case Statement

                               C++ switch...case Statement


The nested if ...else statement allows you to execute a block code among many alternatives. if you are checking on the value of a single variable in nested if.... else statement, it is better to use switch statement.

The switch statement is often faster than nested if....else (not always). Also, the syntax of switch statement is cleaner and easier to understand.


C++ switch......case syntax



When a case constant is found that matches the switch expression, control of the program passes to the block of code associated with that case.

In the above pseudocode, suppouse the value of n is equal to constant2. The compiler will execute the block of code associated with the case statement until the end of switch block, or until the  break ststement is encountered.

The break statement is used to prevent the code running in to the next case.

Flowchart of switch Statement




The  above figur shows how a switch statement works and conditions are checked within the switch case clause.

Example: C++ switch Statement





Output













The - operator entered by the user is stored in o variable. And, two operaands 2.3 and 4.5 are stored in variables num1 and num2 respectively.


Then the control of the program jumps to



Finally, the break statement ends the switch statement.

if  break statement is not used, all cases after the correct case is executed.






0 comments:

Post a Comment

Popular Posts

Recent Posts

Categories

Unordered List

Text Widget