首页 > C/C++在switch中如何从一个标签跳到另外一个.

C/C++在switch中如何从一个标签跳到另外一个.

switch(ch){
    case 1:
    case 2:
    case 3:
    ...
}

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


可以加一个新的case,将case 1 与 case 3中的代码全部复制过去,这样,就完全不影响原来的执行逻辑了。


技术上讲 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;
}

但是同意LS的讲法,你程序逻辑有问题。


一般遇到这种问题,多半是程序逻辑上有问题了。单就这个问题本身,这样做就可以:

#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;
}

加个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 << "world\n";
            }
        }
        case 3:
        {
            cout << "heihei\n";
        }
    }
    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 << "world\n";
            }
        //}
        here:
        case 3:
        {
            cout << "heihei\n";
        }
    }
    return 0;
}
【热门文章】
【热门文章】