3

I have a school project and I'm working on a menu where the users chooses what he wants to do. I want the choice variable to be a char, not an int. Can I add multiple chars in a single switch case? I searched for a solution but I only found one when the value is an int, not a char. I tried this but it didn't work:

char choice;
scanf("%c", &choice); 
switch(choice)
{
case 'S', 's':
    // do something
    break;
case 'I', 'i':
    // do another thing
    break;
default:
    printf("\nUnknown choice!");
    break;
}
S.S. Anne
  • 15,171
  • 8
  • 38
  • 76
iyy0v
  • 51
  • 1
  • 5
  • `'S', 's'` is a comma operator expression evaluating to just the right hand side, `'s'`. – Kaz Mar 10 '20 at 19:29
  • 2
    @Kaz It's not even that, it's a syntax error. A `case` label has to be a constant expression, and those don't include assignment or the comma operator. – dbush Mar 10 '20 at 19:34
  • @dbush It's a syntax error because a *constant-expression* is a *conditional-expression*, and that doesn't include the comma operator grammar production. If we wrap it in parentheses, then the syntax is good, yet the expression is still not a standard constant expression. (That could then work without a diagnostic on some implementations, because ISO C says that "[A]n implementation may accept other forms of constant expressions".) – Kaz Mar 11 '20 at 12:20

3 Answers3

6

You can use fall through like this:

case 'S':
case 's':
    // do something
    break;
case ...
Eraklon
  • 4,206
  • 2
  • 13
  • 29
6

For starters use the following format in scanf

char choice;
scanf( " %c", &choice ); 
       ^^^

(see the blank before the conversion specifier). Otherwise the function will also read white space characters.

You can use several adjacent case labels like for example

switch(choice) 
{
    case 'S':
    case 's': 
        //do something
        break;

    case 'I':
    case 'i': 
        //do anotherthing
        break;

    default: 
        printf("\n Unknown choice !");
        break;
}

An alternative approach is to convert the entered character to the upper case before the switch. For example

#include <ctype.h>

//...

char choice;
scanf( " %c",&choice ); 

switch( toupper( ( unsigned char )choice ) ) 
{
    case 'S':
        //do something
        break;

    case 'I':
        //do anotherthing
        break;

    default: 
        printf("\n Unknown choice !");
        break;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
2

You can put multiple case labels after each other:

switch(choice) {
case 'S':
case 's':
    //do something
    break;
case 'I':
case 'i': 
    //do anotherthing
    break;
default: 
    printf("\n Unknown choice !");
    break;
}
dbush
  • 205,898
  • 23
  • 218
  • 273