Software & Finance





C Programming (Turbo C++ Compiler) - Switch Case Statement





We can write the entire code with if else statements and with out using switch case statement at all. Then why do we need switch case statements? The answer is for program clarity and ease of maintenance.

 

If we have 2 - 4 cases, then we can use if else statements. If we have more number of cases, then still you can proceed with if else, however it is better to use switch case statements.

 

switch(key) - switch will take key as an argument. It can be of numeric integer value only (both positive and negative numbers). It can not accept any floating point numbers or strings. It can accept enums as they are treated as integers.

 

Note: If you do not use break statement after case block, then it will continue executing the next case.


Source Code


int main()

{

 

   enum Location {

        LocUSA, LocUK, LocGermany, LocIndia, LocChina, LocJapan,

        LocPhilippines, LocMalaysia, LocSingapore, LocThailand,

        LocIndonesia, LocOthers

    };

 

    Location key = LocIndia;

 

    switch(key)

    {

    case LocUSA:

        {

            printf("USA");

            break;

        }

    case LocUK:

        {

            printf("UK");

            break;

        }

    case LocGermany:

        {

            printf("Germany");

            break;

        }

    case LocIndia:

        {

            printf("India");

            break;

        }

    case LocChina:

        {

            printf("China");

            break;

        }

    case LocPhilippines:

        {

            printf("Philippines");

            break;

        }

    default:

        {

            printf("Others");

            break;

        }

    };

}

Output


India