Reputation: 31579
In the following code:
int i = 0;
switch(i)
{
case 0:
cout << "In 0" << endl;
i = 1;
break;
case 1:
cout << "In 1" << endl;
break;
}
What will happen? Will it invoke undefined behavior?
Upvotes: 17
Views: 12680
Reputation: 65
Your output would be :
"In 0"
even if you assign the value i = 1 it wont be reflected because switch does not operate in iteration, it is one time selection as break would make it go out of the switch statement.
Upvotes: 0
Reputation: 283763
No undefined behavior. But the value of i
is only tested when the code reaches switch (i)
. So case 1:
will be skipped (by the break;
statement).
The switch
keyword does not mean "run code whenever the value of i
is 0 / 1". It means, check what i
is RIGHT NOW and run code based on that. It doesn't care what happens to i
in the future.
In fact, it's sometimes useful to do:
for( step = 0; !cancelled; ++step ) {
switch (step)
{
case 0:
//start processing;
break;
case 1:
// more processing;
break;
case 19:
// all done
return;
}
}
And changing the control variable inside a case
block is extremely common when building a finite state machine (although not required, because you could set next_state
inside the case
, and do the assignment state = next_state
afterward).
Upvotes: 23
Reputation: 792677
There's no issue here. The expression in the switch condition is evaluated when it is reached. It doesn't have to be a variable and if it is the variable can be subsequently modified without any effect on the behaviour of the switch statement.
Upvotes: 2
Reputation: 57179
You break out of this switch statement after you set it to 1 which is defined behavior so it will never enter case 1
.
Upvotes: 2