替代在C许多情况下,switch语句 [英] Alternative to many case switch statement in C

查看:242
本文介绍了替代在C许多情况下,switch语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个8位字节的重新presents 8个物理开关的状态。我需要做的事情是开关开启和关闭的每个排列不同。我最初的想法是写一个256的情况下switch语句,但它很快就成为繁琐的打字。

I have a 8 bit byte that represents the states of 8 physical switches. I need to do something different for each permutation of switches being on and off. My first idea was to write a 256 case switch statement, but it quickly became tedious to type.

有没有更好的方法来做到这一点?

Is there a better way to do this?

编辑:我本来应该更清楚一点上的功能。我有8个按钮,每做一件事。我需要能够检测是否多个开关一次pssed这样我就可以在同一时间运行两个功能$ P $。

I should have been a bit clearer on the functions. I have 8 buttons that each do one thing. I need to be able to detect if multiple switches are pressed at once so I can run both functions at the same time.

推荐答案

您可以使用函数指针数组。小心指数交由正值 - 一个字符可能会被签署。无论这是比任何使用开关比较繁琐说法是值得商榷的 - 但肯定的执行会更快

You can use an array of function pointers. Be careful to index it by a positive value - a char might be signed. Whether this is any more tedious than using a switch statement is arguable - but execution will certainly be quicker.

#include <stdio.h>

// prototypes
int func00(void);
int func01(void);
...
int funcFF(void);

// array of function pointers
int (*funcarry[256])(void) = {
    func00, func01, ..., funcFF
};

// call one function
int main(void){
    unsigned char switchstate = 0x01;
    int res = (*funcarry[switchstate])();
    printf ("Function returned %02X\n", res);
    return 0;
}

// the functions
int func00(void) {
    return 0x00;
}
int func01(void) {
    return 0x01;
}
...
int funcFF(void) {
    return 0xFF;
}

这篇关于替代在C许多情况下,switch语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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