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': ...
}
}
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.
Important points to C Switch Case Variables are not allowed inside the case label, but integer/character variables are allowed for switch expression.
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.
Yes, you can use scanf() function to get the input from user.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With