Function Pointer

Reference:

  1. Sw@y's Notes: Array of Function Pointers
  2. Stack Overflow: How do I determine the size of my array in C?

1. Function pointer array example:

void run() {  
    printf("start\r\n");  
}  

void stop() {  
    printf("stop\r\n");  
}  

void exit() {  
    printf("exit\r\n");  
}  

static void (*command[])(void) = {run, stop, exit};  

int OnStateChange(int state) {  

    //caculate function pointer array size
    int nArraySize = (sizeof(command) / sizeof(command[0]));    

    if (state > nArraySize) {   
        printf("Wrong state!\n");  
        return false;  
    }  

    //透過function pointer,就不用寫一推if else或是switch來選擇function
    command[state]();                   

    return 0;  
}

results matching ""

    No results matching ""