问题描述
switch(ch){ case 1: case 2: case 3: ...}
如果我想让当ch == 1时程序从运行完case 1的代码直接跳到case 3应该怎么做?
问题解答
回答1:一般遇到这种问题,多半是程序逻辑上有问题了。单就这个问题本身,这样做就可以:
#include <stdio.h>int main(void){int i = 1;switch(i) {case 1:printf('case 1n');case 3:printf('case 3n');break;case 2:printf('case 2n');break;default:break;}return 0;}回答2:
加个flag,这样能满足题主你的需求吗。。。。
#include <iostream>using namespace std;int main(){ int a; cin >> a; bool flag = true; switch(a) {case 1:{ cout << 'hello'; flag = false;}if (flag){case 2: {cout << 'worldn'; }}case 3:{ cout << 'heihein';} } return 0;}
再来个goto版本:
#include <iostream>using namespace std;int main(){ int a; cin >> a; //bool flag = true; switch(a) {case 1:{ cout << 'hello'; goto here;}//if (flag)//{case 2: {cout << 'worldn'; }//}here:case 3:{ cout << 'heihein';} } return 0;}回答3:
技术上讲 goto 可以搞定
#include <stdio.h>int main(void){ int i = 1; switch(i) {case 1: printf('case 1n'); goto eleven; break;case 3:eleven: printf('case 3n'); break;case 2: printf('case 2n'); break;default: break; } return 0;}
但是同意LS的讲法,你程序逻辑有问题。
回答4:可以加一个新的case,将case 1 与 case 3中的代码全部复制过去,这样,就完全不影响原来的执行逻辑了。