简体   繁体   中英

Alternative to many case switch statement in C

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?

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

您可以定义一个函数数组,并使用字节作为数组中的索引,并在数组中的给定位置相应地调用该函数。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM