0

Here if i run the code every case is getting printed and it is not happening if i put the default at the end can you please give me a clarification why it is happening so? Thank u so much in advance for spending time at my question.

enter code here

   #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;
 }
Bharath
  • 1
  • 2
  • [Your compiler might warn with warnings enabled.](https://gcc.godbolt.org/z/f9GG956Wr) – chris May 02 '21 at 07:13
  • 1
    You forgot to put `break` statements in your `switch` statement. As a result, the order of the cases, including the default case, matters, since each case falls through to the one after it. – Tom Karzes May 02 '21 at 07:21
  • How can this question be a duplicate to that one?? – tsh Jun 27 '22 at 02:20
  • This should be a duplicate to https://stackoverflow.com/questions/3110088/switch-statement-must-default-be-the-last-case – tsh Jun 27 '22 at 02:22

2 Answers2

0

This is called case fall-through. First the case that matches the switch-parameter will be executed, then every case after that until the control reaches a break-statement.

In your code no case matches the value 8, so the default will be hit. After executing the default case every case below it will be executed. When the default is first, every case will be executed too.

To prevent this use break-statements as appropiate:

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

case 1:      
    printf("\n Today is Monday");
    break;
...
Lukas-T
  • 11,133
  • 3
  • 20
  • 30
0

I see you haven't included in the the 'break' statement after any cases. Which is causing your code to 'fall-through' and print all the cases. You can google and learn more about the 'break' statement and its significance. The 'default' statement only gets executed when no cases match the test case. So it won't matter where you place it, it will still be checked after all the test cases checked to be a no-match.

Shreya
  • 1
  • 1