【问题标题】:switch case isn't true than also its executing case which is inside the failed oneswitch case 不是正确的,而不是它在失败中的执行 case
【发布时间】:2014-09-21 00:07:05
【问题描述】:
#include<stdio.h>
 int main()
{
     switch(2)
    {
            case 1:
                    if(1)
                    {
                            case 2:
                                    printf("hello\n");
                    };
    }
    return 0;
}

输出 = 你好 当我在switch 中传递2case 1 不正确,然后它也进入它并执行 case 2 内的代码。 怎么会进入case 1? 谢谢。

【问题讨论】:

  • FWIW, switch(2) 也没有多大意义。您通常打开变量的值。 AFAICT,不输入case 1:,直接跳转到case 2:。而if(1) 也没用。

标签: c


【解决方案1】:

switch(2)之后,会立即跳转到case 2标签。它位于case 1 中包含的if 块内这一事实无关紧要。 case 2: 的功能与goto 标签没有什么不同,所以无论它在哪里,它都会跳转到它。以某种方式输入案例 1 是不正确的。

为了澄清,正确缩进它看起来像这样:

#include<stdio.h>
int main() {
  switch(2) {
  case 1:
    if(1) {
  case 2:
      printf("hello\n");
    }
    ;
  }
  return 0;
}

【讨论】:

    【解决方案2】:

    它怎么会进入case 1?

    它不输入case 1。事实上if(1) 在这里没有用。上面的代码等价于

    #include<stdio.h>
    int main()
    {
        switch(2)
        {
            case 1:
            case 2: printf("hello\n");
        }
        return 0;
    }  
    

    要查看if 的不相关用法,您可以将if(1) 替换为if(0),您会发现结果相同。

    【讨论】:

    • 通过它的 o/p 我也知道它类似于 2 你所说的但是,我的问题是如何?
    猜你喜欢
    • 1970-01-01
    • 2020-10-14
    • 2014-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    • 2015-07-16
    • 2021-08-05
    相关资源
    最近更新 更多