Reputation: 197
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.
Upvotes: 4
Views: 626
Reputation: 47729
No, sorry, not in the way that you intend (negating the whole logical expression rather than one of its components). But you can use the default
clause to match anything that wasn't matched by a case
.
Upvotes: 10
Reputation: 62
Each case condition has an int as its conditional value. A character is taken to be a special case of an int. Using the NOT operator has no meaning in a case statement.
Joe's answer is the best one.
Upvotes: 1
Reputation: 6311
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.
Upvotes: 12