Switch statements in C

I am writing a C program with switch statements, and I was wondering if the compiler would accept an operator like

case !('a'): 

I could not find the programs on the Internet that I used ! using the switch statement.

+4
source share
3 answers

No, I'm sorry, not the way you intend (negation of the entire logical expression, not one of its components). But you can use the default clause to match everything that doesn't match case .

+10
source

Did you really try?

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

! is a logical negation operator as well! (x) returns 1 for x from 0 and 0 for anything else. 'a' has a value that is known at compile time, so the compiler evaluates !('a') to 0. So

 case !('a'): 

is equivalent

 case 0 : 

It does not even generate a compiler error and works great.

I believe that this is not what you want to do, and rather you want a case that would catch all the values โ€‹โ€‹except "a", and not a single value of 0. Sorry, but the case-switch statements do not work this way, The expression following the case keyword must be a value known to the compiler.

+12
source

Each condition condition has an int as a conditional value. The symbol is a special case of int. Using the NOT operator does not make sense in a case statement.

The answer is the best answer.

+1
source

Source: https://habr.com/ru/post/1395711/


All Articles