Switch statement using or

谁说胖子不能爱 提交于 2019-11-28 10:43:49

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

The generally accepted syntax for this is:

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

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.

Just use tolower(), here's my man:

SYNOPSIS
#include ctype.h

   int toupper(int c);
   int tolower(int c);

DESCRIPTION toupper() converts the letter c to upper case, if possible.

   tolower() converts the letter c to lower case, if possible.

   If c is not an unsigned char value, or EOF, the behavior of these
   functions is undefined.

RETURN VALUE The value returned is that of the converted letter, or c if the conversion was not possible.

So in your example you can switch() with:

switch(tolower(menuChoice)) {
    case('q'):
        // ...
        break;
    case('s'):
        // ...
        break;
}

Of course you can use both toupper() and tolower(), with capital and non-capital letters.

You could (and for reasons of redability, should) before entering switch statement use tolower fnc on your var.

'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 statement menuChoice would be compared to value of 1 in each case. If menuChoice 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.

switch (toupper(choice))
{
  case 'Q':...
}

...or tolower.

if you do

case('s' || 'S'):
    // some code
default:
    // some code

both s and S will be ignored and the default code will run whenever you input these characters. So you could decide to use

case 's':
case 'S':
    // some code

or

switch(toupper(choice){
    case 'S':
        // some code.

toupper will need you to include ctype.h.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!