【发布时间】:2011-07-19 23:11:51
【问题描述】:
在这个循环中(假设amount是2),而不是打印:
1. [op1]
2. [op2]
打印出来:
1. [op1]
2. [op2]
3. [op3]
4. [op4]
5. [op5]
为什么?我该如何解决这个问题?
for(int i=1;i<=amount;i++){
//string s;
switch(i){
case 1:
cout << i << ". " << op1 << endl;
//s = op1;
case 2:
cout << i << ". " << op2 << endl;
//s = op2;
case 3:
cout << i << ". " << op3 << endl;
//s = op3;
case 4:
cout << i << ". " << op4 << endl;
//s = op4;
case 5:
cout << i << ". " << op5 << endl;
//s = op5;
}
//cout << i << ". " << s << endl;
}
【问题讨论】:
-
把 switch 想象成一个美化的
goto:它跳转到一个案例,然后从那里开始,就好像这个案例是一个标签,而标签是由switch表达式选择的。要停止执行,请在案例末尾使用break;。 -
你应该得到
[op1] [op2] [op3] [op4] [op5] [op2] [op3] [op4] [op5],对吧? -
@Vlad - 是的,这就是 OP 应该得到的。
-
这看起来类似于 Duff 的设备:en.wikipedia.org/wiki/Duff%27s_device
标签: c++ loops for-loop switch-statement