Alternative to many case switch statement in C

2019-06-01 22:16发布

问题:

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.

回答1:

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


回答2:

You can define an array of functions and use the byte as an index in the array and correspondingly call the function in the given position in the array.