Saturday, April 19, 2025

C++ Switch Statement

Switch statements are awesome. They are like menu in games. This is generic example of it:

#include <iostream>

using namespace std;

int main() {

    int menu = 1;

    switch (menu) {
    case 0:
        cout << "Option 0" << endl;
        break;
    case 1:
        cout << "Option 1" << endl;
        break;
    case 2:
        cout << "Option 2" << endl;
        break;
    default:
        cout << "Default Operation" << endl;
        break;
    }

}

For example, if we are creating some menu in DOS/Terminal programs/games we can have something like this code. Run it: 

#include <iostream>

using namespace std;

int main() {

    int menu = 1;

    switch (menu) {
    case 0:
        cout << "Video Controls" << endl;
        break;
    case 1:
        cout << "Audio Controls" << endl;
        break;
    case 2:
        cout << "Update Game" << endl;
        break;
    default:
        cout << "Please Correct your Input" << endl;
        break;
    }

}

Result 

Audio Controls

Process returned 0 (0x0)   execution time : 0.057 s
Press any key to continue.

 Outside it we will have come hard-coded choice (simple example):

int menu = 1;

Then it's time to open switch statement:

switch (menu) {

And then we handle cases, one by one, in this case for menu value 0:

case 0:
    cout << "Video Controls" << endl;
    break;

Break is needed because there's no point going into other options if some specific is already chosen.

Default is needed as last possible option, where nothing else can be chosen:

default:
        cout << "Please Correct your Input" << endl;
        break;
    }

Switch Statement with Keyboard Input

This is practical one, we are not hard-coding choice but taking it with keyboard:


#include <iostream>

using namespace std;

int main() {

    int menu;

    cout << "Please, enter Choice: " << endl;
    cin >> menu;

    switch (menu) {
    case 0:
        cout << "Video Controls" << endl;
        break;
    case 1:
        cout << "Audio Controls" << endl;
        break;
    case 2:
        cout << "Update Game" << endl;
        break;
    default:
        cout << "Please Correct your Input" << endl;
        break;
    }

}

Result:

Please, enter Choice:
2
Update Game

Process returned 0 (0x0)   execution time : 1.894 s
Press any key to continue.

Nice and useful.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...