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?
If a programmer declares variables, initializes them before the first case statement, and then tries to use them inside any of the case statements, those variables will have scope inside the switch block but will not be initialized and will consequently contain indeterminate values.
Important points to C Switch CaseVariables are not allowed inside the case label, but integer/character variables are allowed for switch expression. Break and default are optional.
Explanation: The switch/case statement in the c language is defined by the language specification to use an int value, so you can not use a float value.
You can use the break statement to end processing of a particular labeled statement within the switch statement. It branches to the end of the switch statement. Without break , the program continues to the next labeled statement, executing the statements until a break or the end of the statement is reached.
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).
You break out of this switch statement after you set it to 1 which is defined behavior so it will never enter case 1
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With