### Switch Statements

I was studying switch statements but I can not figure out its outputs. I get totally wrong values. Consider the following codes. The outputs are 4, 4 and 5. Can you kindly explain how those are the outputs because I thought the outputs will be 3, 4 and 3.

CODE 1

int x = 2;
switch (x)
{
case 1: x+=2;
case 2: x++;
case 3: x++;
cout << ”The value of x is: ” << x;
break;
default:
cout << ”The value of x is: ” << x;
}

CODE 2

int x = 3;
switch (x)
{
case 1: x+=2;
case 2: x++;
case 3: x++;
cout << ”The value of x is: ” << x;
break;
default:
cout << ”The value of x is: ” << x;
}

CODE 3

int x = 1;
switch (x)
{
case 1: x+=2;
case 2: x++;
case 3: x++;
cout << ”The value of x is: ” << x;
break;
default:
cout << ”The value of x is: ” << x;
}
Last edited on
CODE 1

x is set to 2. Then inside switch as the expression x is equal to 2 the control is passed to label case 2:
x is incremented and becomes equal to 3.
The control is passed to the next statement that is to statement marked with label case 3:
x is incremented and becomes equal to 4. Its value equal to 4 is outputed and due to break statement the control is passed outside the switch.

int x = 2;
switch (x)
{
case 1: x+=2;
case 2: x++;
case 3: x++;
cout << ”The value of x is: ” << x;
break;
default:
cout << ”The value of x is: ” << x;
}

CODE 2

x is set to 3. Then inside switch as the expression x is equal to 3 the control is passed to label case 3:
x is incremented. Its value equal to 4 is outputed and due to break statement the control is passed outside the switch.

int x = 3;
switch (x)
{
case 1: x+=2;
case 2: x++;
case 3: x++;
cout << ”The value of x is: ” << x;
break;
default:
cout << ”The value of x is: ” << x;
}

CODE 3

x is set to 1. Then inside switch as the expression x is equal to 1 the control is passed to label case 1:

x is added 2. x becomes equal to 3. The control is passed to the next statement marked with label case 2:
x is incremented and becomes equal to 4. The control is passed to the next statement marked with label case 3:
x is again is incremented and becomes equal to 5.
Its value equal to 5 is outputed and due to break statement the control is passed outside the switch.

int x = 1;
switch (x)
{
case 1: x+=2;
case 2: x++;
case 3: x++;
cout << ”The value of x is: ” << x;
break;
default:
cout << ”The value of x is: ” << x;
}
Last edited on
After each case, you need a break statement. Otherwise the code will just continue to the next case in line. Thus, in the first example, it went to case 2, incremented x once, then the code continued to the next line, and incremented x again.

It doesn't make logical sense. It would make sense if each case had an automatic break, but it doesn't. That's why it's fun!
Ohhhh yes I understand now.. For the outputs to be what I initially thought to be, breaks has to be included after each case otherwise the next cases will be executed! Yes its fun! Thank u so much guys
Topic archived. No new replies allowed.