1,457 views
1 votes
1 votes
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??

2 Answers

1 votes
1 votes

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. 

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.

Related questions

1 votes
1 votes
1 answer
1
0 votes
0 votes
1 answer
2
joshi_nitish asked Jun 28, 2017
578 views
BREAK can be used in switch-case but CONTINUE is not allowed in switch-case but CONTINUE is allowed in DEFAULT case of switch-case..is it correct??
3 votes
3 votes
2 answers
3
Sankaranarayanan P.N asked Oct 27, 2016
410 views
What will be the output of the following C program fragment?int n =1; switch(n) { case 1: printf("One"); case 2: printf("Two"); case 3: case 4: case 5: default: printf("W...