首页 > 解决方案 > c ++ switch语句:对案例进行分组并为每个案例提供特定说明

问题描述

考虑以下代码:

int main()
{
    const int a = 9;
    switch (a)
    {
    case 9:
        // since a is 9, this ("good") should be printed
        std::cout << " good " << std::endl;

    case 4:
        // since a is not 4, this ("bad") should not be printed
        std::cout << " bad " << std::endl;

        // for both a==9 or a==4, this should be printed
        {
            std::cout << " always print me " << std::endl;
            break;
        }
    }
}

结果应该是:

good
always print me

但是,这是行不通的。有没有办法在 C++ 中做到这一点?谢谢!

标签: c++switch-statement

解决方案


switch除了 using 之外,没有办法在-statement中执行您要求的操作goto

#include <iostream>

int main()
{
    const int a{ 9 };

    switch (a)
    {
    case 9:
        std::cout << "good\n";
        goto foo;

    case 4:
        std::cout << "bad\n";
        goto foo;

    foo:
        std::cout << "always print me\n";
        break;
    }
}

推荐阅读