Code

Switch-Case

Switch-Case ( case structure )

The switch statement is a control statement, which is different from if statement because it evaluates a single expression against a list of multiple possible cases. Every case is related to the single expression and must end with the break or goto case, or an empty block. The break statement passes control out of the switch. You can omit a break statement if two cases lead to the same action.

With a default Label

The default case is optional and is executed if no other case applies. It’s also a common practice to code the default label last for easy reading.

switch default

Run Demo

OUTPUT

Unknown number!

With goto statement

goto keyword causes the execution to jump to a new location in the code. The target location is defined by the marker in the code – called label. Check the example below.

goto switch statement

Run Demo

OUTPUT

Case: B

switch Statement that falls through the second case label

If one or more case labels are empty, execution will follow the code of the next case block which contains code. This allows grouping of multiple case labels with the same implementation.

Note: If a case block is not empty, a break must be present before the next case label, otherwise the compiler will generate an error.

switch fall through

Run Demo

OUTPUT

Case: One and Two

Add Comment

Click here to post a comment

Subscribe

Most Popular

Popular Video