Switch Statements in C++ Programming Language

Switch case statements are a substitute for long if statements that compare a variable with multiple values. Once a match is found, it executes the corresponding code for that value case. In this article, I will walk you through switch statements in C ++ programming language.

Introduction to Switch Case Statements in C ++

In the C ++ programming language, the switch statement causes control to be transferred to one of many statements based on the value of a condition.

Also, Read – Break and Continue Statements in C++ Programming Language.

The keyword switch is followed by a condition in parentheses and a block, which can contain case labels and an optional default label. When the switch statement is executed, control will be transferred either to a case label with a value matching that of the condition, if applicable, or to the default label, if applicable.

The condition must be an expression or a declaration, which has an integer type or enumeration, or a class type with a convert function to an integer type or enumeration.

Now let’s see how to write a program using these statements in C ++ programming language:

#include<iostream>
using namespace std;

int main(){
    char button;
    cout<<"Input a character: ";
    cin>>button;
    switch (button)
    {
    case 'a':
        cout<<"Hello"<<endl;
        break;
    case 'b':
        cout<<"Namaste"<<endl;
        break;
    case 'c':
        cout<<"Salut"<<endl;
        break;
    default:
    cout<<"Still learning more";
        break;
    }
}

The variable in the switch statements must have a constant value. The break statement is optional, it ends the switch statement and moves control to the next line after the switch.

If the break statement is not added, the switch statement will not end and will continue on the next line after the switch statement. Each case value must be unique. The default case is optional. But it is important because it is executed when no case value can be matched.

So these are the fundamentals of Switch case statements in the C++ programming language. I hope, you liked this article on the switch case statements in C++ programming language. Feel free to ask your valuable questions in the comments section below.

Aman Kharwal
Aman Kharwal

I'm a writer and data scientist on a mission to educate others about the incredible power of data📈.

Articles: 1498

Leave a Reply