user11376749
user11376749

Reputation:

cannot understand the output for switch statement for input 3

I am not getting this..please help me find the way of evaluation of this code. (input is 3)

int a = 9, b;

scanf("%d", &b);

switch(a+b)
{
    case 3:
        a+= b * 2 - (a-b);
        b = a + b;
    default:
        a-= b * 2 - (a-b);
        b = a - b;
    case 9:
        a+= a * 3 - (a-b);
        b = a/b;
        break;
    case 5:
        a%=b;
}
printf("a = %d\nb = %d\n",a,b);

the output for input 3 is(actual) :

33 5

shouldn't it be like this following two's(expected) :

9 6

Upvotes: 1

Views: 62

Answers (2)

dbush
dbush

Reputation: 224427

There is no break statement at the end of the 3 or default cases, so the code falls through to the following cases until a break is encountered or until the end of the switch is reached.

Be sure to add a break after every case. Also, the default case should go at the bottom by convention:

switch(a+b)
{
    case 3:
        a+= b * 2 - (a-b);
        b = a + b;
        break;
    case 9:
        a+= a * 3 - (a-b);
        b = a/b;
        break;
    case 5:
        a%=b;
        break;
    default:
        a-= b * 2 - (a-b);
        b = a - b;
        break;
}

Upvotes: 1

Sabrina Jewson
Sabrina Jewson

Reputation: 1518

The reason why it isn't working is that after default: finishes, there is no break; so control continues into the code for case 9. Here is it fixed:

int a = 9, b;

scanf("%d", &b);

switch(a+b)
{
    case 3:
        a+= b * 2 - (a-b);
        b = a + b;
        break;
    case 5:
        a%=b;
        break;
    case 9:
        a+= a * 3 - (a-b);
        b = a/b;
        break;
    default:
        a-= b * 2 - (a-b);
        b = a - b;
        break;
}
printf("a = %d\nb = %d\n",a,b);

Also, it is better for readability to order the cases in some way, not just randomly; default also always goes at the bottom.

Upvotes: 1

Related Questions