Hi friends,

i am doing a basic menu based Car rental system in C. i have a doubt regarding switch...

do C permit us to use multiple switch case? or a Case within a Case??

"Multiple switch" case, I am not sure what you mean by this. Checking for multiple cases is what you'd typically use a switch for so yes, multiple "case" statements are allowed.

Nesting a switch within a switch is also allowed. The switch body is just a normal or compound statement which can contain any other valid c labels. In fact, you could also use case statements there without a switch.

A little example:

#include <stdio.h>
int main()
{
    int a = 1, b = 2;

    switch(a)
    {
        case 1:
            printf("Falling through..\n");

        case 2:
            printf("Falling through..\n");

        case 3:
            printf("Falling through..\n");

        case 4:
        {
            switch(b)
            {
                case 1:
                    printf("b is 1.\n");
                    break;

                case 2:
                    printf("b is 2.\n");
                    break;

                case 3:
                    printf("b is 3.\n");
                    break;

                default:
                    printf("b is undefined!\n");
                    break;
            }
        } break;

        case 5:
        {
            case 6:
                printf("a is 6!\n");
                break;
        }

        default:
            printf("At the bottom.\n");
    }

    return 0;
}

When run, it will output:

Falling through..
Falling through..
Falling through..
b is 2.

because 1 is one, but the case bodies of the other switch don't break out of it using 'break'. As a result the case statements are executed in order. This is called "fallthrough".

At some point the body for case 4 is reached which contains a new switch statement. This is valid. For example purposes I DID add 'break' statements for every case now which is why only the following is shown:

b is 2.

Note that a break will only break out of the inner switch. The other would still fall through if no break was following the switch.

As another example I included only a label for the body of switch 5 for the outer switch construction. If a were to be 6, it would jump to that label, even if it's part of another label.

-edit-

For clarity: I added parenthesis in case 4/5 for readability. They are not needed. For 5 especially I wanted to accent that the label is part of a case body.

thanks Gonbe... its a great help... i need a help of yours again.... as i am progressing with the work... i am a newbie to C :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.