Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch statement using or

I'm creating a console app and using a switch statement to create a simple menu system. User input is in the form of a single character that displays on-screen as a capital letter. However, I do want the program to accept both lower- and upper-case characters.

I understand that switch statements are used to compare against constants, but is it possible to do something like the following?

switch(menuChoice) {     case ('q' || 'Q'):         //Some code         break;     case ('s' || 'S'):         //More code         break;     default:         break; } 

If this isn't possible, is there a workaround? I really don't want to repeat code.

like image 774
Saladin Akara Avatar asked Jan 16 '11 11:01

Saladin Akara


People also ask

Can I use || in switch-case?

You can't use “||” in case names. But you can use multiple case names without using a break between them. The program will then jump to the respective case and then it will look for code to execute until it finds a “break”. As a result these cases will share the same code.

Does switch use == or ===?

Yes, switch "[uses] the strict comparison, === ".

Can switch have 2 arguments?

Yes, this is valid, because in this case, the , is a comma operator.

Can we use or operator in switch-case in C?

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.


1 Answers

This way:

 switch(menuChoice) {     case 'q':     case 'Q':         //Some code         break;     case 's':     case 'S':         //More code         break;     default:  } 

More on that topic: http://en.wikipedia.org/wiki/Switch_statement#C.2C_C.2B.2B.2C_Java.2C_PHP.2C_ActionScript.2C_JavaScript

like image 189
Chris Hasiński Avatar answered Sep 22 '22 05:09

Chris Hasiński