C: Switch Statements Sometimes when creating a C program, you run into a situation in which you want to compare one thing to a number of other things. Let's say, for example, that you took a character from the user and wanted to compare this to a number of characters to perform different actions. Switch Case statement in C with example By Chaitanya Singh Filed Under: Learn C Switch case statement is used when we have multiple conditions and we need to perform different action based on the condition. When we have multiple conditions and we need to execute a block of statements when a particular condition is satisfied.
What is a Switch Statement?
Switch statement tests the value of a variable and compares it with multiple cases. Once the case match is found, a block of statements associated with that particular case is executed.
Each case in a block of a switch has a different name/number which is referred to as an identifier. The value provided by the user is compared with all the cases inside the switch block until the match is found.
If a case match is NOT found, then the default statement is executed, and the control goes out of the switch block.
In this tutorial, you will learn-
Syntax
A general syntax of how switch-case is implemented in a 'C' program is as follows:
- The expression can be integer expression or a character expression.
- Value-1, 2, n are case labels which are used to identify each case individually. Remember that case labels should not be same as it may create a problem while executing a program. Suppose we have two cases with the same label as '1'. Then while executing the program, the case that appears first will be executed even though you want the program to execute a second case. This creates problems in the program and does not provide the desired output.
- Case labels always end with a colon ( : ). Each of these cases is associated with a block.
- A block is nothing but multiple statements which are grouped for a particular case.
- Whenever the switch is executed, the value of test-expression is compared with all the cases which we have defined inside the switch. Suppose the test expression contains value 4. This value is compared with all the cases until case whose label four is found in the program. As soon as a case is found the block of statements associated with that particular case is executed and control goes out of the switch.
- The break keyword in each case indicates the end of a particular case. If we do not put the break in each case then even though the specific case is executed, the switch will continue to execute all the cases until the end is reached. This should not happen; hence we always have to put break keyword in each case. Break will terminate the case once it is executed and the control will fall out of the switch.
- The default case is an optional one. Whenever the value of test-expression is not matched with any of the cases inside the switch, then the default will be executed. Otherwise, it is not necessary to write default in the switch.
- Once the switch is executed the control will go to the statement-x, and the execution of a program will continue.
Flow Chart Diagram of Switch Case
Following diagram illustrates how a case is selected in switch case:
Example
Following program illustrates the use of switch:
Switch Case C++ 11
Output:
- In the given program we have initialized a variable num with value 8.
- A switch construct is used to compare the value stored in variable num and execute the block of statements associated with the matched case.
- In this program, since the value stored in variable num is eight, a switch will execute the case whose case-label is 8. After executing the case, the control will fall out of the switch and program will be terminated with the successful result by printing the value on the output screen.
Try changing the value of variable num and notice the change in the output.
For example, we consider the following program which defaults:
Output:
When working with switch case in C, you group multiple cases with unique labels. You need to introduce a break statement in each case to branch at the end of a switch statement.
The optional default case runs when no other matches are made.
We consider the following switch statement:
Output:
Nested Switch
In C, we can have an inner switch embedded in an outer switch. Also, the case constants of the inner and outer switch may have common values and without any conflicts.
We considere the following program which the user to type his own ID, if the ID is valid it will ask him to enter his password, if the password is correct the program will print the name of the user, otherwise ,the program will print Incorrect Password and if the ID does not exist , the program will print Incorrect ID
OUTPUT:
- In the given program we have initialized two variables: ID and password
- An outer switch construct is used to compare the value entered in variable ID. It execute the block of statements associated with the matched case(when ID500).
- If the block statement is executed with the matched case, an inner switch is used to compare the values entered in the variable password and execute the statements linked with the matched case(when password000).
- Otherwise, the switch case will trigger the default case and print the appropriate text regarding the program outline.
Why do we need a Switch case?
There is one potential problem with the if-else statement which is the complexity of the program increases whenever the number of alternative path increases. If you use multiple if-else constructs in the program, a program might become difficult to read and comprehend. Sometimes it may even confuse the developer who himself wrote the program.
The solution to this problem is the switch statement.
Rules for switch statement:
- An expression must always execute to a result.
- Case labels must be constants and unique.
- Case labels must end with a colon ( : ).
- A break keyword must be present in each case.
- There can be only one default label.
- We can nest multiple switch statements.
Summary
- A switch is a decision making construct in 'C.'
- A switch is used in a program where multiple decisions are involved.
- A switch must contain an executable test-expression.
- Each case must include a break keyword.
- Case label must be constants and unique.
- The default is optional.
- Multiple switch statements can be nested within one another.
Allows selection among multiple sections of code, depending on the value of an integral expression.
Syntax
switch (
[initialization;
] expression)
{
case
constant-expression:
statement[
default :
statement]}
Remarks
The expression must have an integral type, or be a class type that has an unambiguous conversion to integral type. Integral promotion takes place as described in Standard conversions.
The switch statement body consists of a series of case labels and an optional default label. Collectively, the statements that follow the labels are called labeled statements. The labeled statements aren't syntactic requirements, but the switch statement is meaningless without them. No two constant expressions in case statements may evaluate to the same value. The default label may appear only once. The default statement is often placed at the end, but it can appear anywhere in the body of the switch statement. A case or default label can only appear inside a switch statement.
The constant-expression in each case label is converted to the type of expression. Then, it's compared with expression for equality. Control passes to the statement whose caseconstant-expression matches the value of expression. The resulting behavior is shown in the following table.
Switch statement behavior
Condition | Action |
---|---|
Converted value matches that of the promoted controlling expression. | Control is transferred to the statement following that label. |
None of the constants match the constants in the case labels; a default label is present. | Control is transferred to the default label. |
None of the constants match the constants in the case labels; no default label is present. | Control is transferred to the statement after the switch statement. |
If a matching expression is found, execution can continue through later case or default labels. The
break
statement is used to stop execution and transfer control to the statement after the switch statement. Without a break statement, every statement from the matched case label to the end of the switch, including the default, is executed. For example:In the above example,
uppercase_A
is incremented if c
is an uppercase 'A'
. The break statement after uppercase_A++
terminates execution of the switch statement body and control passes to the while loop. Without the break statement, execution would 'fall through' to the next labeled statement, so that lowercase_a
and other
would also be incremented. A similar purpose is served by the break statement for case 'a'
. If c
is a lowercase 'a'
, lowercase_a
is incremented and the break statement terminates the switch statement body. If c
isn't an 'a'
or 'A'
, the default statement is executed.Visual Studio 2017 and later: (available with /std:c++17) The
[[fallthrough]]
attribute is specified in the C++17 standard. You can use it in a switch statement. It's a hint to the compiler, or anyone who reads the code, that fall-through behavior is intentional. The Microsoft C++ compiler currently doesn't warn on fallthrough behavior, so this attribute has no effect on compiler behavior. In the example, the attribute gets applied to an empty statement within the unterminated labeled statement. In other words, the semicolon is necessary.Visual Studio 2017 version 15.3 and later (available with /std:c++17). A switch statement may have an initialization clause. It introduces and initializes a variable whose scope is limited to the block of the switch statement:
An inner block of a switch statement can contain definitions with initializations as long as they're reachable, that is, not bypassed by all possible execution paths. Names introduced using these declarations have local scope. For example:
A switch statement can be nested. When nested, the case or default labels associate with the closest switch statement that encloses them.
Microsoft-specific behavior
C++ Switch Case Loop
Microsoft C doesn't limit the number of case values in a switch statement. The number is limited only by the available memory. ANSI C requires at least 257 case labels be allowed in a switch statement.
The default for Microsoft C is that the Microsoft extensions are enabled. Use the /Za compiler option to disable these extensions.
Switch Case In C Syntax
See also
C++ Switch Case Multiple
Selection Statements
Keywords
Keywords