ccgt ccgt - 3 months ago 6
C Question

which it is the difference of using single quotes ' ' in switch statement case

which is the difference of writing

case '1' or case 1

or also write

case 'a' or case a

it differs write ' and not write

Answer

'1' is a character constant, and its value is the encoding for that character (49 in ASCII). So writing

case '1':

is equivalent to writing

case 49:

on an ASCII system.

Use case '1': when you want to take a particular action on seeing the character '1'. Use case 1: when you want to take a particular action on seeing the integer value 1.

Edit

Note that you can't write case a: if a is a variable; all case labels must be constant expressions, meaning their value must be known at compile time. This means a case label needs to be an expression consisting only of integer or character constants (or macros that evaluate to such). So the only way case a: would be legal is if a is a macro that expands to a constant expression.

Comments