C function pointers

后端 未结 3 1868
攒了一身酷
攒了一身酷 2021-01-25 00:04
static void increment(long long *n){
  (*n)++;
}

struct test{
  void (*work_fn)(long long *);
};

struct test t1;

t1.work_fn = increment;

How do I ac

3条回答
  •  被撕碎了的回忆
    2021-01-25 00:48

    You can call it as t1.work_fn(&n) or as (*t1.work_fn)(&n), whichever you prefer.

    Symmetrically, when assigning the pointer you can do either t1.work_fn = increment or t1.work_fn = &increment. Again, it is a matter of personal coding style.

    One can probably argue that for the sake of consistency one should stick to either "minimalistic" style

    t1.work_fn = increment;
    t1.work_fn(&n);
    

    or to a "maximalistic" style

    t1.work_fn = &increment;
    (*t1.work_fn)(&n);
    

    but not a mix of the two, so that we can have well-defined holy wars between two distinctive camps instead of four.

    P.S. Of course, the "minimalistic" style is the only proper one. And one must crack eggs on the pointy end.

提交回复
热议问题