Curriculum
Course: C basic
Login

Curriculum

C basic

C Introduction

0/1

C Get Started

0/1

C Comments

0/1

C Constants

0/1

C Operators

0/1

C Break and Continue

0/1

C User Input

0/1

C Memory Address

0/1

C Structures

0/1
Text lesson

C Switch

Switch Statement

Instead of employing numerous if…else statements, you can utilize the switch statement.

The switch statement chooses one of multiple code blocks to execute.

Syntax

switch (expression) {
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
}

Here’s how it functions:

  • The switch expression undergoes evaluation just once.
  • The expression’s value is compared against each case’s value.
  • When a match is found, the corresponding block of code is executed.
  • The break statement terminates the switch block and halts execution.
  • The default statement, which is optional, specifies code to run if no case matches.

The following example utilizes the weekday number to determine the corresponding weekday name:

Example

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;
}

// Outputs “Thursday” (day 4) 

The break Keyword

When C encounters a break keyword, it exits the switch block, halting the execution of any further code and case testing within that block.

Once a match is found and the required task is completed, it’s necessary to break out. Additional testing becomes unnecessary at that point.

Using a break can significantly save execution time since it effectively skips the execution of all remaining code within the switch block.

The default Keyword

The default keyword designates code to execute if no case matches are found:

Example

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”);
}

// Outputs “Looking forward to the Weekend” 

 

Note: The default keyword should be positioned as the final statement within the switch block, and it does not require a break statement.