C 中的 switch 语句
我正在用 switch 语句用 C 语言编写一个程序,我想知道编译器是否会接受这样的语句,例如
case !('a'):
我在网上找不到任何使用 !
和 switch 语句的程序。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你真的尝试过吗?
嗯,我做到了(Mac OS X 上的 gcc)。
!是逻辑否定运算符,当 x 为 0 时,!(x) 返回 1,对于其他值,则返回 0。
'a'
的值在编译时已知,因此编译器将!('a')
计算为 0。 So相当于
It does not甚至产生编译器错误,并且运行良好。
不过,我认为这不是您想要做的,而是想要一个能够捕获除“a”之外的所有值的 case,而不是单个值 0。抱歉,但 switch-case 语句不能以这种方式工作。
case
关键字后面的表达式必须是编译器已知的值。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. Sois the equivalent of
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.不,抱歉,不是按照您想要的方式(否定整个逻辑表达式而不是其组成部分之一)。但您可以使用
default
子句来匹配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 acase
.每个 case 条件都有一个 int 作为其条件值。字符被视为 int 的特殊情况。在 case 语句中使用 NOT 运算符没有任何意义。
乔的回答是最好的。
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.