search

Home  >  Q&A  >  body text

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

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

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

迷茫迷茫2803 days ago554

reply all(4)I'll reply

  • 阿神

    阿神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;
    }

    reply
    0
  • ringa_lee

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

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

    reply
    0
  • 大家讲道理

    大家讲道理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.

    reply
    0
  • Cancelreply