Hello!

I have a problem about creating a menu, the switch statement doesn't break. Could somebody please help?

The code is:

        do
        {
            /* ...get input... */
            switch(choice)
            {
            case 1:
                submenu();
                break;
            case 2:
                submenu2();
                break;
            case 3:
                printf("\nThe program quits.\n");
                exit(0);
            default:
                printf("\nNo such menu item!\n\n");
                break;
            }
        }
        while(choice != 1 || choice != 2 || choice != 3);

After calling submenu or submenu2 it executes the corresponding method, but after, it returns to the get input part again. What am I missing here?

Thanks in advance!

Your do..while condition is self defeating. Try using && instead of ||.

That would mean that the input should be 1 AND 2 AND 3 in the same time, not?

EDIT: it's working the way you said but why? Could you please explain it? Thx!

That would mean that the input should be 1 AND 2 AND 3 in the same time, not?

You're comparing inequality, not equality. So if the input is not 1, not 2, and not 3 then the loop will continue.

The reason why the && condition worked was because of the following reasons:
when you compare something with the and (&&) logical operator then even if the first case fails, then the system does not need to go and check the remaining of the conditions.
for your example if we use the && instead of the ||

while(choice != 1 && choice != 2 && choice != 3);

then according to the boolean logic for and (&&)

Suppose:
A && B = C

A B C
0 0 0
0 1 0
1 0 0
1 1 1

so if choice had value 1 then the condition choice !=1 fails and then the system does not check ahead as it knows that the condition has failed, and to get out of the loop.

However if the conditions were using or (||) as shown in your example:

while(choice != 1 || choice != 2 || choice != 3);

then if choice has the value 1 then your condition will always be true because your other conditions will be true even though your first condition failed, and your loop will not end.

A || B = C

A B C
0 0 0
0 1 1
1 0 1
1 1 1

i hope that this helped you in understanding the basics.

  while(choice != 1 && choice != 2 && choice != 3);

It means repeat above until the value is apart from 1,2 or 3(until the statement is true).

Hmm. :) Thank you everyone, I think I'm getting the point!

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.