【问题标题】:what if we use Default first in switch case in c [duplicate]如果我们在 c 中的 switch case 中首先使用 Default 怎么办 [重复]
【发布时间】:2021-07-24 23:25:14
【问题描述】:

在这里,如果我运行代码,每个案例都会被打印出来,如果我把默认值放在最后,它就不会发生,你能告诉我为什么会这样吗? 非常感谢您花时间回答我的问题。

在此处输入代码

   #include <stdio.h>

   int main()
   {

     int weekday=8;

    switch (weekday)
  {
     
 default:
    
  printf("\n Please enter Valid Number between 1 to 7");     
 
 case 1:
      
  printf("\n Today is Monday");
      
  case 2:
      printf("\n Today is Tuesday");
      
  case 3:
      printf("\n Today is Wednesday"); 
      
  case 4:
      printf("\n Today is Thursday"); 
      
  case 5:
      printf("\n Today is Friday"); 
      
  case 6:
      printf("\n Today is Saturday");
      
  case 7:
      printf("\n Today is Sunday");
      

   }

   printf("\n%d",weekday);
  
return 0;
 }

【问题讨论】:

标签: c++ c switch-statement


【解决方案1】:

这称为案例失败。首先执行与 switch-parameter 匹配的 case,然后执行之后的每个 case,直到控件到达 break-statement。

在您的代码中,没有 case 与值 8 匹配,因此将命中 default。在执行默认案例后,它将执行下面的每个案例。当default 是第一个时,every case 也会被执行。

为防止这种情况,请适当使用break-statements:

switch (weekday)
{
default:    
    printf("\n Please enter Valid Number between 1 to 7");     
    break;

case 1:      
    printf("\n Today is Monday");
    break;
...

【讨论】:

    【解决方案2】:

    我看到您在任何情况下都没有包含在“break”语句中。这导致您的代码“失败”并打印所有案例。 您可以 google 并了解有关“break”声明及其意义的更多信息。 'default' 语句仅在没有与测试用例匹配的情况下执行。所以不管你把它放在哪里,在所有的测试用例都检查为不匹配之后,它仍然会被检查。

    【讨论】:

      猜你喜欢
      • 2011-12-22
      • 2021-12-08
      • 2021-05-09
      • 1970-01-01
      • 2014-11-09
      • 2012-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多