Monday, January 6, 2025
HomeTechSwitch Statement in C++

Switch Statement in C++

The switch statement in C++ is used to execute one of several possible code blocks based on the value of an expression. It is an alternative to using multiple if-else conditions.

Syntax:

cpp
switch (expression) {
case constant1:
// Code block for constant1
break;
case constant2:
// Code block for constant2
break;
default:
// Code block if no match
}

Key Points:

  1. expression: Typically an integer or character.
  2. case: Compares the expression to the value. If matched, the corresponding block is executed.
  3. break: Exits the switch statement after a case is executed (optional but recommended).
  4. default: Executes if no case matches.
See also  How to Find Hidden Apps on Android

Example:

cpp
#include <iostream>
using namespace std;

int main() {
int day = 3;

switch(day) {
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
default:
cout << "Invalid day";
}

return 0;
}

  • The switch statement is efficient for handling multiple conditional branches based on a single expression.
RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x