"I think MISRA C disallows function pointers, partly for this reason."
Are function pointers really bad things?
Sincerely I found them useful and lastly I was using them more and more. Am I wrong?
Function pointers help me in at least three situation.
With function pointer I can isolate C modules from the rest of the project, so it is much more simple to create a well-define hardware abstraction layer that let me improve portability to other hw platforms, but mostly let me create a "simulator" on the development machine.
For example, consider a simple leds module interface:
int leds_init(void (*on_fn)(uint8_t idx), void (*off_fn)(uint8_t idx)); int led_on(uint8_t led_idx); int led_off(uint8_t led_idx); int led_toggle(uint8_t led_idx); int led_blink(uint8_t led_idx); int leds_on_all(void); ...
Here the important function is leds_init() with function pointers arguments that really switch on or off the LED idx. I call leds_init() in this way:
leds_init(bsp_led_on, bsp_led_off);
On target bsp_led_on() manages GPIO registers or SPI GPIO expander and so on, on development machine bsp_led_on() could be a printf() or a different icon on a GUI.
In this context, functions pointers help to have testability modules. If I want to test leds module, the test code could call leds_init() in this way:
leds_init(test_led_on, test_led_off);
So during tests it's much simpler to break the links between modules and insert the test suite where it is necessary.
Another nice thing that is possible with function pointers is to make some OOP tricks, for example polymorfism.
Of course one drawback of using function pointers is stack usage calculation (see my previous post): it would be impossible to make a calc, because the tool can't resolve the function pointer call.