switch(ch){
case 1:
case 2:
case 3:
...
}
如果我想让当ch == 1
时程序从运行完case 1
的代码直接跳到case 3
应该怎么做?
阿神2017-04-17 14:32:05
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;
}
ringa_lee2017-04-17 14:32:05
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;
}
怪我咯2017-04-17 14:32:05
Technically speaking goto
it can be done
#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.
大家讲道理2017-04-17 14:32:05
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.