Switch in C

the use of switch statement in C, and also the syntax of switch statement

Last Reviewed and Updated on February 7, 2020
Posted by Parveen(Hoven),
Aptitude Trainer and Software Developer

My C/C++ Videos on Youtube

Here is the complete playlist for video lectures and tutorials for the absolute beginners. The language has been kept simple so that anybody can easily understand them. I have avoided complex jargon in these videos.

The switch statement in C is one of the aids to decision making. It mimics the behaviour of a knob that could be seen in older washing machines and microwave ovens. A fan regulator that lets you decide the speed at which to run the fan is another example of a switch.

Use Scenarios of a switch

Consider a menu based program where you want your end user to enter his choice. Let's say we ask him to enter an alphabet, and we have to show him a word that starts with that alphabet, just like we have kindergarten books that teach the English alphabet. The user has 27 possiblities here - 26 are for the alphabet, and 1 for an invalid value. We have to handle 27 branches. The code that will ultimately execute depends only on one thing - his input - which can be called the switch expression. This is a fit case for using a switch. A developer could build this program entirely with an if-else ladder, without using a switch at all; but that's not recommended for a situation like this. We have to use the right instrument for the right task.

Another situation where a switch has been used is in software written with the Windows C API(also called the Win32 API). When a window, such as a notepad or your browser, etc., is created, the Windows OS runs a message loop. The code below has been extracted from Microsoft MSDN. This code shows a typical message loop.

while( (bRet = GetMessage( &msg, NULL, 0, 0 )) != 0)
{ 
    if (bRet == -1)
    {
        // handle the error and possibly exit
    }
    else
    {
        TranslateMessage(&msg); 
        DispatchMessage(&msg); 
    }
} 
 

This message loop is an infinite while loop that keeps on forwarding messages to a function that can be specified by a programmer. These messages could be from a mouse event, or keyboard event, or when a user clicks any button. Each of these messages has a numeric code associated with it. A switch statement is used as a decision statement to run the appropriate statements. The code below has been extracted from Microsoft MSDN. This code shows the usage of a switch statement. Don't worry if you donot understand the tough looking parts of this code, they take quite some time before a new developer can make sense out of them.

LRESULT CALLBACK MainWndProc(
    HWND hwnd, // handle to window
    UINT uMsg, // message identifier
    WPARAM wParam, // first message parameter
    LPARAM lParam) // second message parameter
{ 

    switch (uMsg) 
    { 
    case WM_CREATE: 

        // Initialize the window. 
        return 0; 

    case WM_PAINT: 

        // Paint the window's client area. 
        return 0; 

    case WM_SIZE: 

        // Set the size and position of the window. 
        return 0; 

    case WM_DESTROY: 

        // Clean up window-specific data objects. 
        return 0; 

        // 
        // Process other messages. 
        // 

    default: 

        return DefWindowProc(hwnd, uMsg, wParam, lParam); 

    } 

    return 0; 
} 

The switch Syntax

The syntax can be understood through a program. A switch is written with the switch keyword. The switch body contains case labels for the switch. The code inside a case label executes if the value of the switch expression matches the case label. The switch expression must evaluate to whole number integer. It could be an int, char, long, short, etc., but it cannot be a float, double or a string or any other non-integral. In the following program, x is called the switch expression. It is of an integral whole number type, and depending on its value, the corresponding case label will be entered. The role of the switch expression is limited only to deciding the entry point case label.

int main()
{
    int x = 2;
 
    // x is the switch expression
    switch (x)
    {
        // code for this label runs if x is 0
    case 0:
        {
            cout << "Zero" << endl;
            break;
        }
    
        // code for this label runs if x is 1
    case 1:
        {
            cout << "One" << endl;
            break;
        }
 
        // code for this label runs if x is 2
    case 2:
        {
            cout << "Two" << endl;
            break;
        }
    
        // code for this label runs if x is 3
    case 3:
        {
            cout << "Three" << endl;
            break;
        }
    
        // code for this label runs if x is anything else
    default:
        {
            cout << "Not from 0, 1 , 2 or 3" << endl;
        }
    }
 
    return 0;
}

Apart from the case labels, there is a trump-card like label called the default label. The code inside this label executes if the switch expression doesn't match any of the case labels in the switch.

In the above code, you have probably noticed the break keyword also. A break is used to end the processing of a case label and jump out of the switch. A break statement short circuits any statements that may be present after the break. If a production code contains statements after a break, then it is surely a careless programming. Such a code is called unreachable code. Of course I am referring to the statements inside a case label.

The case labels must be unique. Dupicate case labels are not allowed; it's a compiler error.

Fall through

When a case label doesn't end in a break, then it's called a fall through. Consider the code below. There is no break statement. We have removed the break statements in all the case labels including the default label. If x is 0, the code for case 0 will run followed by the codes of the remaining labels and the default label in the same sequence in which they appear inside the switch. This is called a fall through. Similarly, if the user enters 1, then code for all labels from case 1 will be executed. The code for case 0 will not be executed because it is above the label 1.

int main()
{
    int x = 2;
 
    // x is the switch expression
    switch (x)
    {
        // code for this label runs if x is 0
    case 0:
        {
            cout << "Zero" << endl;
        }
    
        // code for this label runs if x is 1
    case 1:
        {
            cout << "One" << endl;
        }
 
        // code for this label runs if x is 2
    case 2:
        {
            cout << "Two" << endl;
        }
    
        // code for this label runs if x is 3
    case 3:
        {
            cout << "Three" << endl;
        }
    
        // code for this label runs if x is anything else
    default:
        {
            cout << "Not from 0, 1 , 2 or 3" << endl;
        }
    }
 
    return 0;
}

A fall through is not always an omission, but it can lead to inadvertent bugs if the developer isn't careful. But despite all the pitfalls, it is one of the widely used features of a switch statement. Here is a code that shows an appropriate use. This code returns the correct output even if the caps lock is ON. Notice how a long chain of case labels and the fall through have helped us write our code concisely.

int main()
{
    cout << "Enter a char: ";
 
    char k;
 
    cin >> k
 
    // x is the switch expression
    switch (k)
    {
        case 'a':
        case 'A':
        case 'e':
        case 'E':
        case 'i':
        case 'I':
        case 'o':
        case 'O':
        case 'u':
        case 'U':
            {
                cout << "It's a vowel." << endl;
                break;
            }
        default:
            {
                cout << "It's a consonant." << endl;
            }
    }
 
    return 0;
}

Miscellanoues Features of a switch in C

How many Case Labels are Allowed inside a switch?The ANSI C Standard specifies that a compiler should support atleast 257 case labels. There is no upper limit. Some compilers like Visual C++ allow an infinite number of case labels inside a switch.

Switch inside a switch?Switch statements can be nested. This means that a case label can contain a switch statement.

Any other uses of the default and case keywords? The ANSI C language doesn't allow the use of case and default keywords for any other purpose. This means that these two keywords can be used only inside a switch.

Variables inside a switch but outside the case labels? It's possible. For a complete discussion please refer the video below.

Classroom Training

Classroom training in C/C++ is available at our training institute. Click here for details. You can also register yourself here.

Video Tutorial

We have created a video tutorial that can be downloaded and watched offline on your windows based computer. It is in the form of an exe file. No installation is required, it runs by double clicking the file. Since the exe file is hosted on the Google Drive, it should be very safe because Google itself checks for any virus or malware. The video can be watched offline, no internet is required.

Pricing

This single video will cost you USD $5. When you download the video, you will be able to watch the first few minutes for free, as a sample. The video app will prompt you for payment through PayPal and other payment options. If you want ALL VIDEOS, NOT JUST THIS ONE then go here: Complete Set of C/C++ Video Tutorials The entire set is priced at USD $50.

Screenshots

This is a screenshot of the software that should give you a good idea of the available functionality. Click on the image to see a larger view.screenshot of the video being played in the software

Installation

This software doesn't require any installation. Just download and double-click to run it. It doesn't require administrative priviliges to run. It runs in limited access mode, so should be very safe.

supports windows xp and later Supported Operating Systems

These videos can be run on 32-bit as well as 64-bit versions of the Microsoft Windows Operating Systems. Windows XP and all later OS are supported. If you want to run it on Windows XP and Windows Vista, then you must also have the .NET Framework Version 3.5 installed on your machines. Those users who have Windows 7 and later donot have to worry because these operating systems already have the .NET Framework installed on them.

Download Links

IMPORTANT NOTE: This download contains ONLY ONE video. The video is about the topic of this tutorial.

Want ALL Videos? If you want ALL VIDEOS, NOT JUST THIS ONE then go here: Complete Set of C/C++ Video Tutorials. TIP: If you plan to buy these videos, then it would be more economical to buy the entire set.

DISCLAIMER: Even though every care has been taken in making this software bug-free, but still please take a proper backup of your PC data before you use it. We shall not be responsible for any damages or consequential damages arising out of the use of this software. Please use it solely at your own risk.

Please download the software here.
download the video Switch in C



Creative Commons License
This Blog Post/Article "Switch in C" by Parveen (Hoven) is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
Updated on 2020-02-07. Published on: 2015-10-05