Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch statements in C

I am writing a program in C with switch statements and I was wondering if the compiler will accept a statement such as

case !('a'):

I couldn't find any programs online that used the ! with a switch statement.

like image 560
Sams Avatar asked Nov 28 '22 17:11

Sams


1 Answers

Did you actually try it?

Well, I did (gcc on Mac OS X).

! is the logical negation operator, and !(x) returns 1 for an x of 0, and 0 for anything else. 'a' has a value which is known at compile-time, so the compiler evaluates !('a') to 0. So

case !('a'):

is the equivalent of

case 0 :

It doesn't even generate a compiler error, and runs fine.

I take it that's not what you want to do, though, and rather want a case that will catch all values except 'a', rather than the single value 0. Sorry but switch-case statements don't work that way. The expression following the case keyword has to be a value known to the compiler.

like image 164
Paul Richter Avatar answered Dec 01 '22 08:12

Paul Richter