简体   繁体   English

在C中切换语句

[英]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 我正在使用switch语句在C语言中编写程序,我想知道编译器是否会接受诸如的语句

case !('a'):

I couldn't find any programs online that used the ! 我在网上找不到任何使用过的程序! with a switch statement. 带有switch语句。

Did you actually try it? 你真的尝试过吗?

Well, I did (gcc on Mac OS X). 好吧,我做了(Mac OS X上的gcc)。

! is the logical negation operator, and !(x) returns 1 for an x of 0, and 0 for anything else. 是逻辑否定运算符,并且!(x)返回1表示x为0,其他为0。 'a' has a value which is known at compile-time, so the compiler evaluates !('a') to 0. So 'a'具有在编译时已知的值,因此编译器将!('a')为0.所以

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. 我认为这不是你想要做的,而是想要一个能够捕获除'a'之外的所有值的情况,而不是单个值0.抱歉但是switch-case语句不能那样工作。 The expression following the case keyword has to be a value known to the compiler. case关键字后面的表达式必须是编译器已知的值。

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 . 但是您可以使用default子句匹配case不匹配的任何内容。

Each case condition has an int as its conditional value. 每个case条件都有一个int作为其条件值。 A character is taken to be a special case of an int. 字符被认为是int的特例。 Using the NOT operator has no meaning in a case statement. 使用NOT运算符在case语句中没有意义。

Joe's answer is the best one. 乔的答案是最好的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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