堆叠switch语句c ++

时间:2014-04-05 04:42:05

标签: c++

我只是想知道我们是否可以将switch case语句堆叠起来,例如,将另一个案例导入另一个案例等等。我目前正计划如何制作我的项目,但我需要确认是否可能

1 个答案:

答案 0 :(得分:1)

好吧,我将添加一种有趣的方式来实现它。

警告:我实际上不会这样做,这只是一种做你喜欢的事情。

#include<iostream>

int main()
{
    int foo = 0;
    switch ( foo ) 
    {
    case 0 :
        goto that;
        break;
    case 1 :
that :
        std::cout << 'b';
        goto theOther; 
        break;
    case 2 :
theOther :
        std::cout << 'a';
        goto andAnother;
        break;
    case 3 :
andAnother :
        std::cout << 'r';
        break;
    }
    return 0;
}

你不能&#34;堆叠&#34;他们自由。在C ++中,如果你删除了break语句,它将会#34;通过&#34;。例如,这将得到相同的结果......

#include<iostream>

int main()
{
    int foo = 0;
    switch ( foo ) 
    {
    case 0 :
    case 1 :
        std::cout << 'b';
    case 2 :
        std::cout << 'a';
    case 3 :
        std::cout << 'r';
    }
    return 0;
}

前者允许你做的是......

#include<iostream>

int main()
{
    int foo = 0;
    switch ( foo ) 
    {
    case 0 :
        goto andAnother; 
        break;
    case 1 :
that :
        std::cout << 'b'; 
        break;
    case 2 :
theOther :
        std::cout << 'a';
        goto that;
        break;
    case 3 :
andAnother :
        std::cout << 'r';
        goto theOther;
        break;
    }
    return 0;
}