Switch statement and increment operator

I wrote the following code:

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

The result of the code was like this:

01  
1

Can someone explain the first line of output? Why are 0 and 1 printed?

+3
source share
4 answers

First, an expression i++(post-increment operator) evaluates to 0 (even if it sets the value ito 1). Therefore switch, a branch is selected inside case 0:.

Then, since after case 0:no break, the program continues to execute the code in the label case 1:.

To summarize, you have: 0 from the first branch switch, 1 from the second branch, and the other 1, because the last value i.

+18
source

break , . .

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

, ,

+7

"break;" .

+2

- . C, Java # , "-OO".

, OO, .

, "jump", , O (1) , "if". ( ) , "" , "break".

Here's how it was done in C and saved for C ++.

As for the value in the switch, it should be a numeric value, but it does not have to be a constant. In your case, it i++evaluates to 0, but increases me to 1. This is a well-defined behavior, and there are no problems with sequence points.

0
source

All Articles