简体   繁体   中英

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.

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.

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM