Switch in C
Instead of writing multiple if..else statements, you can use the switch statement in C. The Switch statement in C selects one of many blocks of code to be executed.
Instead of writing many if.else statements , you can use switch statements in C. The Switch statement in C selects one of many blocks of code to be executed.
Basic syntax of Switch in C
switch(expression) { case x: // code block break; case y: // code block break; default: // code block }
Here's how it works:
- The expression
switch
is evaluated once. - The value of the expression is compared with the value of each case.
- If there is a match, the relevant block of code will be executed.
- The command
break
exits the switch block and stops execution. - The command
default
is optional, specifying some code to run if there is no matching case.
The example below uses the number of days of the week to calculate the day of the week:
For example:
#include int main() { int day = 4; switch (day) { case 1: printf("Monday"); break; case 2: printf("Tuesday"); break; case 3: printf("Wednesday"); break; case 4: printf("Thursday"); break; case 5: printf("Friday"); break; case 6: printf("Saturday"); break; case 7: printf("Sunday"); break; } return 0; }
Break keyword
When C reaches the keyword break
, it will exit the switch block. This action will stop further code deployment and test cases inside the block. When a suitable case is found, it means the job is complete. Now is the time to rest, no need for further testing.
A break can save a lot of implementation time because it skips execution of all the remaining code in the switch block.
Default keyword
Keywords default
specify some code to run if there is no matching case. For example:
#include int main() { int day = 4; switch (day) { case 6: printf("Today is Saturday"); break; case 7: printf("Today is Sunday"); break; default: printf("Looking forward to the Weekend"); } return 0; }
Note: The keyword default
must be used as the last command in switch
and it does not require a break.
Above are the things you need to know about Switch in C. Hope the article is useful to you.
You should read it
- How does the LAN switch (LAN switch) work?
- Ways to Power Off Nintendo Switch
- How to use the SWITCH function in Excel 2016
- How to add a passcode to Nintendo Switch
- How to capture screen and record video on Nintendo Switch game console
- Top 5 Best Ethernet Switch 2021
- Review of PoE 8 Port TP-Link Switch TL-SG1008P: Indispensable for home security
- How to update games on Nintendo Switch
- How to turn an old router into a switch
- How to play Airship map in Among Us on Switch
- How to fix Joy-Con error on Nintendo Switch
- Distinguish between switches, routers and modems