在C中获取开关箱中的箱数 [英] Getting the number of cases in a switch-case in C

查看:67
本文介绍了在C中获取开关箱中的箱数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在C语言的切换案例中获得案例数,而无需手动添加在每种情况下递增的计数器变量?

Is it possible to get the number of cases in a switch case in C without manually adding a counter variable which is incremented in each case?

推荐答案

正如我之前评论的,我认为您想要一个调度表而不是switch语句。这是一个小例子。

As I commented earlier, I think you want a dispatch table rather than a switch statement. Here's a little example.

说出来了:

int find_the_case();
void do_something();
void do_something_different();
void do_something_completly_different();
void do_default();

int main(int argc, char *argv[])
{
    int c = find_the_case();
    switch(c){
        case 0:
           do_something();
           break;
        case 1:
           do_something_different();
           break;
        case 5:
           do_something_completly_different();
           break;
        default:
           do_default();
           break;
    }
    return 0;
}

现在可以将其重写为:

#define MAX_NUMBER_OF_CASES 6
int main_dispatchtable()
{
    void (*table[MAX_NUMBER_OF_CASES])(void)  = {
            [0] = do_something,
            [1] = do_something_different,
            [5] = do_something_completly_different
    };

    int c = find_the_case();
    if( table[c] )
            table[c]();
    else
            do_default();

    /* for the counting */
    int count = 0;
    for (int i = 0; i < MAX_NUMBER_OF_CASES; i++ )
            if( table[i] ) count++;

    return 0;
}

与使用switch语句相比,这通常是一种更好的方法。它不仅使添加更多案件更加容易,而且还可以对案件进行计数。如果您有一个庞大的表而稀疏的情况,则可以使用哈希表而不是普通数组。

This is usually a much better way than using switch statements. Not only does it make it simpler to add more cases, but it also allows counting of cases. If you have a huge table and sparse cases you can use a hash table instead of a plain array.

编辑:
当然,使用$ h与切换案例相比,调度表更为丰富,因为您可以动态地添加,删除和更改调度表。那可能是最大的优势。

Of course there are even more advantages with the dispatch table than the switch case, as you can add and remove and change the dispatch table dynamically. That may be the greatest advantage.

这篇关于在C中获取开关箱中的箱数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆