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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With