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.
'q' || 'Q'
results in bool type result (true) which is promoted to integral type used in switch condition (char) - giving the value 1. If compiler allowed same value (1) to be used in multiple labels, during execution of switch statementmenuChoice
would be compared to value of 1 in each case. IfmenuChoice
had value 1 then code under the first case label would have been executed.Therefore suggested answers here use character constant (which is of type char) as integral value in each case label.
...or tolower.
The generally accepted syntax for this is:
i.e.: Due the lack of a
break
, program execution cascades into the next block. This is often referred to as "fall through".That said, you could of course simply normalise the case of the 'menuChoice' variable in this instance via toupper/tolower.
This way:
More on that topic: http://en.wikipedia.org/wiki/Switch_statement#C.2C_C.2B.2B.2C_Java.2C_PHP.2C_ActionScript.2C_JavaScript
You could (and for reasons of redability, should) before entering switch statement use tolower fnc on your var.
Just use
tolower()
, here's my man:So in your example you can
switch()
with:Of course you can use both
toupper()
andtolower()
, with capital and non-capital letters.