C++ switch case Statement – C# Programming Example
C++

C++ switch case Statement

The syntax of the switch instruction is a bit peculiar. Its objective is to check several possible constant values for an expression, something similar to what we did at the beginning of this section with the linking of several if and else if sentences. Its form is the following:

It works in the following way: switch evaluates expression and checks if it is equivalent to constant1, if it is, it executes block of instructions 1 until it finds the break keyword, then the program will jump to the end of the switchselective structure.
If expression was not equal to constant1 it will check if expression is equivalent to constant2. If it is, it will execute block of instructions 2 until it finds the break keyword.
Finally, if the value of expression has not matched any of the previously specified constants (you may specify as many case sentences as values you want to check), the program will execute the instructions included in the default:section, if this one exists, since it is optional.

Both of the following code fragments are equivalent:

I have commented before that the syntax of the switch instruction is a bit peculiar. Notice the inclusion of the break instructions at the end of each block. This is necessary because if, for example, we did not include it after block of instructions 1 the program would not jump to the end of the switch selective block (}) and it would continue executing the rest of the blocks of instructions until the first appearance of the break instruction or the end of the switch selective block. This makes it unnecessary to include curly brackets { } in each of the cases, and it can also be useful to execute the same block of instructions for different possible values for the expression evaluated. For example:

 

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: