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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
No undefined behavior. But the value of
iis only tested when the code reachesswitch (i). Socase 1:will be skipped (by thebreak;statement).The
switchkeyword does not mean “run code whenever the value ofiis 0 / 1″. It means, check whatiis RIGHT NOW and run code based on that. It doesn’t care what happens toiin the future.In fact, it’s sometimes useful to do:
And changing the control variable inside a
caseblock is extremely common when building a finite state machine (although not required, because you could setnext_stateinside thecase, and do the assignmentstate = next_stateafterward).