3

I wrote the following code:

int i = 0;  
switch(i++)  
{
   case 0:  
     cout << 0;  
   case 1:  
     cout << 1;
}  
cout << "\n" << i;  

The output of the code was like this:

01  
1

Can anyone please explain the first line of output? Why are 0 and 1 both being printed?

Jon
  • 428,835
  • 81
  • 738
  • 806
AvinashK
  • 3,309
  • 8
  • 43
  • 94
  • Greatest Design Flaw in any language: http://programmers.stackexchange.com/questions/55047/what-is-the-greatest-design-flaw-you-have-faced-in-any-programming-language/55128#55128 `switch` rated the first position for this stupid (and error prone) behavior. – Matthieu M. Mar 08 '11 at 10:45

4 Answers4

18

First, the expression i++ (post-increment operator) evaluates to 0 (even though it sets the value of i to 1). So inside the switch, the case 0: branch is selected.

Then, because there is no break after your case 0:, the program continues with executing the code in the case 1: label.

Summing it up, you have: 0 from the first switch branch, 1 from the second branch, and another 1 because that's the final value of i.

Jon
  • 428,835
  • 81
  • 738
  • 806
7

Because you need to add a break after each case, which prevents execution of the following statements. E.g.

switch(i++)  
{
   case 0:  
     cout<<0;  
     break;
   case 1:  
     cout<<1;
     break;
}  

Admittedly, the second break is superfluous but I put it there just for the sake of consistency

dandan78
  • 13,328
  • 13
  • 64
  • 78
2

you need to put "break;" at the end of each case.

Eamonn McEvoy
  • 8,876
  • 14
  • 53
  • 83
0

switch is a strange construct. It comes from C, and Java and C# adopted it too, so it is not considered totally "non-OO".

switch on state which changes is a valid OO concept, but often is used for switching based on type.

In particular the compiler usually creates a "jump" table which means it is O(1) what block of code gets called, unlike a nested "if" statement. You may have multiple values (not including default) jump to the same point, thus code blocks "run into" each other unless you explicitly insert a "break" statement.

This is how it was done in C and has been retained for C++.

With regards to the value in the switch, it must be a numeric value but does not have to be a constant. In your case i++ evaluates to 0 but increments i to 1. This is well-defined behaviour and there is no issues with sequence points here.

CashCow
  • 30,981
  • 5
  • 61
  • 92
  • it is a postincrement operator, right. so,it will get incremented after doing its job in the expression of which it is a part....so is it like after it has printed 0, it increments itself and then goes to case 1 – AvinashK Mar 08 '11 at 11:03