C language - Can I use char for switch beside number in cases?

Viewed 53

I want to let user input + or - or * or / but I dont know how to use them in switch so I have to make user input number to represent the arithmetic sign like 1 for + 2 for - and so on... That way I can use switch.

2 Answers

You may. For example

char c = '+';

switch( c )
{
case '+':
    puts( "Plus" );
    break;
case '-':
    puts( "Minus" ); 
    break;
default:
    puts( "Unknown operation" );
    break;
}

According to the C Standard (6.8.4.2 The switch statement)

3 The expression of each case label shall be an integer constant expression and no two of the case constant expressions in the same switch statement shall have the same value after conversion. There may be at most one default label in a switch statement. (Any enclosed switch statement may have a default label or case constant expressions with values that duplicate case constant expressions in the enclosing switch statement.)

And character literals are integer constants.

Here is a very quick and dirty example:

char a='+';  

switch(a) 
{
    case '+' : //do plus stuff;
      break
    case '-' : //do minus stuff;
      break;
    default:  // Say illegal input or whatever;  
      break;
}
Related