in Programming in C
1,438 views
1 vote
1 vote
int main()
{ int a =50;
    switch(a)
    {
        default: a=45;
        case 49: a++;
        case 50: a--;
        case 51: a =a+1;
    }
    printf("%d",a);
}

my doubt is the default case is not executed here why??, what is a value of a  the end??

in Programming in C
1.4k views

3 Comments

edited by
The default case is executed only when there is no matching case; here case 50 exists, therefore, default will not be executed.
And as there is no break after case 50, case 51 will also be executed.
So,

a--;  a=49

a=a+1;  a=49+1

O/P= 50

*position of default doesn't matter
1
1
If in same problem (no break is present)  and default statement is also after our selected case (in the end).  Then what would be the result ?
0
0
The position of default doesn't matter, it will do what it is intended to do:

 executed only when there is no matching case
0
0

2 Answers

1 vote
1 vote

lets try to understand whats happening here : 

value of a assigned to 50. this value of a=50 is fed as an argument to switch case.

which goes to :        case 50: a--;   (a=a-1 (internally ))

                                value of a =49 

now case 51 : a=a+1 will also be executed and  : a= 49+1 =50

If you don't include break in any of case then all the case below will be executed and until it sees break.

so value of a at the end 50 result.

my doubt is the default case is not executed here why??, what is a value of a  the end??

its because the argument fed into switch () will  go to the case containg that argument

and if argument of switch() doesnot belong to any case statement than only it will execute default case. 

by
0 votes
0 votes
The position of default matters.

You can check it on any compiler available.

Here in this switch case  when a =50 is passed as argument in the switch it will go to case 50 and starts executing the statements until a break is encountered.

Let say if a is 95 means the control shifts to the default case and all the statements below default case will run and the o/p will be 46.

2 Comments

sorry I dont agree on that::

please correct me if anything wrong in here:

 

#include<stdio.h>

int main() {
    int i=1;
  switch(i)
  {
      
      case 1: printf("1\n");
      case 2: printf("2\n");
      
      
      case 3: printf("3\n");
      default:printf("default\n");
  }
}

output:

1
2
3
default

 

so default case may get executed in this case also when the case matches.

0
0

@Markzuck  yes are correct for example in the code given below 

#include<stdio.h>

int main()
{ int a =50;
    switch(a)
    {
       
        case 49: a++;
        case 50: a--;
        default: a=45;
        case 51: a =a+1;
    }
    printf("%d",a);
}

 

the result is 46,that means first it  goes to case matching i.e case 50 and then as there is no default all cases after it will also executed

0
0