在案例中更改开关变量 [英] Changing switch variable inside a case
问题描述
在以下代码中:
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?
推荐答案
没有未定义的行为.但是,仅当代码到达 switch(i)
时才测试 i
的值.因此,情况1:
将被跳过(通过 break;
语句).
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).
switch
关键字并不意味着只要 i
的值为0/1,就运行代码".这意味着,请检查 i
现在是什么,然后基于该代码运行代码.不管将来 i
会发生什么.
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;
}
}
在构建有限状态机时,在 case
块内更改控制变量非常普遍(尽管不是必需的,因为您可以在内设置
,然后再分配 next_state
情况 state = next_state
).
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).
这篇关于在案例中更改开关变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!