How is the default keyword used in C++?

In C++, the default keyword can be used in a switch statement to represent a code block that will be executed if the value of the switch expression does not match any case. Here is an example:

int num = 2;
switch(num) {
    case 1:
        cout << "Number is 1" << endl;
        break;
    case 2:
        cout << "Number is 2" << endl;
        break;
    default:
        cout << "Number is not 1 or 2" << endl;
}

In the example above, if the value of num is 1, it will print “Number is 1”; if the value of num is 2, it will print “Number is 2”; if the value of num is neither 1 nor 2, it will print “Number is not 1 or 2”. The default here is to handle the situation where the switch expression does not match any case.

bannerAds