C语言 在 C 中使用逻辑运算符切换大小写

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13226124/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 04:18:43  来源:igfitidea点击:

Switch case with logical operator in C

cswitch-statementor-operator

提问by Er Avinash Singh

I am new to C and need help. My code is the following.

我是 C 新手,需要帮助。我的代码如下。

 #include<stdio.h>  
 #include<conio.h>  
 void main()
 {

  int suite=2;  

  switch(suite)
     {           
      case 1||2:
      printf("hi");

      case 3:
      printf("byee");

      default:
      printf("hello");
     }

  printf("I thought somebody");
  getche();
  }

I am working in Turbo C and the output is helloI thought somebody. There's no error message.

我在 Turbo C 中工作,输出为helloI thought somebody. 没有错误信息。

Please, let me know how this is working.

请让我知道这是如何工作的。

回答by Jeyaram

case 1||2:

Becomes true. so it becomes case 1:but the passed value is 2. so default case executed. After that your printf("I thought somebody");executed.

成为true。所以它变成了case 1:但传递的值是 2。所以默认情况下执行。在那之后你printf("I thought somebody");被处决了。

回答by Aniket Inge

do this:

做这个:

switch(suite){
  case 1:/*fall through*/
  case 2: 
    printf("Hi");
...
}

This will be a lot cleaner way to do that. The expression 1||2evaluates to 1, since suitewas 2, it will neither match 1 nor 3, and jump to defaultcase.

这将是一个更干净的方法来做到这一点。该表达式的1||2计算结果为1,因为suite它是 2,它既不会匹配 1 也不会匹配 3,并跳转到default大小写。

回答by Ed S.

case 1||2:

Results in

结果是

case 1:

because 1 || 2evaluates to 1(and remember; only constant integral expressions are allowed in casestatements, so you cannot check for multiple values in one case).

因为1 || 2计算结果为1(并记住;在case语句中只允许使用常量整数表达式,因此您不能在一个中检查多个值case)。

You want to use:

你想使用:

case 1:
  // fallthrough
case 2:

回答by stefanB

You switchon value 2, which matches defaultcase in switchstatement, so it prints "hello" and then the last line prints "I thought somebody".

switch在 value 上2,它与语句中的defaultcase匹配switch,所以它打印“你好”,然后最后一行打印“我以为有人”。

回答by Harpreet Vishnoi

case (1||2):
  printf("hi");

Just put brackets and see the magic.

只需放上括号,就能看到神奇之处。

In your code,the program just check the first value and goes down.Since,it doesn't find 2 afterwards it goes to default case.

在您的代码中,程序只检查第一个值并关闭。因为,之后它没有找到 2 它进入默认情况。

But when you specific that both terms i.e. 1 and 2 are together, using brackets, it runs as wished.

但是,当您使用括号指定两个术语(即 1 和 2)在一起时,它会按预期运行。