Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do an OR in Switch-Case in C++

How would you do this in C++? For example I'm trying to trigger a program exit both if the user presses ESC or 'q' or 'Q'.

I've tried looking for it, but I found no syntax for it in C++. I know how to do it with if-else, but is it possible with switch - case? Of course I can just make a function and call it from two separate case, but is there a way to do it just by combined case statement?

For example that's what I'm looking for (of course not working):

void keyboard( unsigned char key, int x, int y )
{
    switch( key )
    {
        case ( 27 || 'q' || 'Q' ):
            exit( 0 );
            break;

        case 'a': ...

                case 'b': ...
    }
}
like image 351
hyperknot Avatar asked Jul 17 '12 17:07

hyperknot


People also ask

Can you do or in a case switch?

The logical OR operator (||) will not work in a switch case as one might think, only the first argument will be considered at execution time.

Can we use int in switch case in C?

Important points to C Switch Case Variables are not allowed inside the case label, but integer/character variables are allowed for switch expression.

Can you put a switch in a switch in C?

It is possible to have a switch as a part of the statement sequence of an outer switch. Even if the case constants of the inner and outer switch contain common values, no conflicts will arise.

Can we use Scanf in switch case in C?

Yes, you can use scanf() function to get the input from user.


1 Answers

Cases fall through without a break:

case  27: //could be 27
case 'q': //could be 27 or 'q'
case 'Q': //could be 27, 'q', or 'Q'
    exit(0);
    break;
like image 136
chris Avatar answered Oct 22 '22 06:10

chris