If-statement vs function pointer

后端 未结 6 829
时光说笑
时光说笑 2021-01-04 14:22

The goal is to change the behaviour in an event loop, depending on whether a checkbox is toggled on or off. The simplest way, that I can think of, is just to test the checkb

6条回答
  •  情话喂你
    2021-01-04 15:00

    Imho, pointers are a bit cleaner for calling routines having many arguments:

    int good(int a, int b, int c, char *d) { ... }
    int bad (int a, int b, int c, char *d) { ... }
    int ugly(int a, int b, int c, char *d) { ... }
    

    Direct calls:

    if (is_good) {
       good(1,2,3,"fire!");
    } else if (is_bad) {
       bad(1,2,3,"fire!");
    } else {
       ugly(1,2,3,"fire!");
    }
    

    Indirect calls:

    if (is_good) {
       f = good;
    } else if (is_bad) {
       f = bad;
    } else {
       f = ugly;
    }
    
    ...
    
    f(1,2,3,"fire!");
    

提交回复
热议问题