Download as rtf, pdf, or txt
Download as rtf, pdf, or txt
You are on page 1of 3

Switch statement in C programming is a control flow statement used to perform different actions

based on different conditions. Here's an overview of the switch statement in C:

Syntax of switch statement:

switch (expression) {

case constant1:

// Code to be executed if expression equals constant1

break;

case constant2:

// Code to be executed if expression equals constant2

break;

// More cases can follow

default:

// Code to be executed if none of the above cases are true

Explanation:

expression is evaluated, and its value is compared with each case constant.

If expression matches a case constant, the code block under that case is executed until a break
statement is encountered.

If no match is found, the code block under default (optional) is executed.

break statements are crucial; without them, the execution will continue to the next case without
checking for conditions.

Example:

Copy code

#include <stdio.h>
int main() {

int choice;

printf("Enter a number between 1 to 3: ");

scanf("%d", &choice);

switch (choice) {

case 1:

printf("You entered 1\n");

break;

case 2:

printf("You entered 2\n");

break;

case 3:

printf("You entered 3\n");

break;

default:

printf("Invalid choice\n");

return 0;

Key Points:

switch is used for multiway branching, providing a neater alternative to multiple if-else statements.

The case constants must be integral values (integers or characters) and unique within the same switch.

Each case label ends with a break statement to prevent fall-through to the next case.
The default case is optional and executes when no matching case is found.

Nested switch statements are allowed for more complex scenarios.

It's important to note that the switch statement can only compare values, not conditions, and it doesn't
support comparing strings directly (prior to C99). Also, each case value should be unique; having
duplicate case values will result in a compilation error.

Understanding switch statements in C allows programmers to efficiently handle multiple conditions


within their code, making it more readable and maintainable.

You might also like