C/C++在switch中如何从一个标签跳到另外一个.
迷茫
迷茫 2017-04-17 14:30:05
0
4
558
switch(ch){
    case 1:
    case 2:
    case 3:
    ...
}

如果我想让当ch == 1时程序从运行完case 1的代码直接跳到case 3应该怎么做?

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(4)
阿神

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

#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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template