switch(ch){ case 1: case 2: case 3: ... }
如果我想让当ch == 1时程序从运行完case 1的代码直接跳到case 3应该怎么做?
ch == 1
case 1
case 3
业精于勤,荒于嬉;行成于思,毁于随。
Generally if you encounter this kind of problem, it is mostly due to a problem in the program logic. For the question itself, just do this:
#include <stdio.h> int main(void) { int i = 1; switch(i) { case 1: printf("case 1\n"); case 3: printf("case 3\n"); break; case 2: printf("case 2\n"); break; default: break; } return 0; }
Add a flag, can this meet your needs? . . .
#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 << "world\n"; } } case 3: { cout << "heihei\n"; } } return 0; }
Another goto version:
#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 << "world\n"; } //} here: case 3: { cout << "heihei\n"; } } return 0; }
Technically speaking goto it can be done
goto
#include <stdio.h> int main(void) { int i = 1; switch(i) { case 1: printf("case 1\n"); goto eleven; break; case 3: eleven: printf("case 3\n"); break; case 2: printf("case 2\n"); break; default: break; } return 0; }
But I agree with LS, there is something wrong with your program logic.
You can add a new case and copy all the codes in case 1 and case 3. In this way, the original execution logic will not be affected at all.
Generally if you encounter this kind of problem, it is mostly due to a problem in the program logic. For the question itself, just do this:
Add a flag, can this meet your needs? . . .
Another goto version:
Technically speaking
goto
it can be doneBut I agree with LS, there is something wrong with your program logic.
You can add a new case and copy all the codes in case 1 and case 3. In this way, the original execution logic will not be affected at all.