C supports pointers to functions. Functions are not variables but you can define a pointer to a function. The function name refers to the address of the function much like array name points to first element.
lets define a function , this function takes a integer as parameter and prints it
you can define a pointer to this function as follows
The use of the functional pointer is very similar to how we call a function
The full program looks something like this
We can also pass the functional pointers to other functions.Continuing with the previous example , let us assume that there is method which expects a functional pointer as a parameter to print its output
7 | void printSomething( int (*printFuncPtr)( int )){ |
21 | printSomething(funcPtr); |
You can use typedef to define the functional pointer
2 | typedef int (*ptr)( int ); |
8 | void frmtPrint(ptr ptr1){ |
Lets a real world example where we use functional pointers.
MQTT is publish/subscribe based messaging protocol. PubSubClient is one of the library available for arduino.
To receive messages from broker , you need a set a callback function, So your code will be invoked by the library when there is new message on the subscribed channels. The following snippet is from PubSubClinet example mqtt_basic
1 | client.setCallback(callback); |
here callback is function name
1 | void callback( char * topic, byte * payload, unsigned int length) { |
2 | Serial.print( "Message arrived [" ); |
5 | for ( int i= 0 ;i<length;i++) { |
6 | Serial.print(( char )payload[i]); |
The function signature should match with that of expected by the library
1 | #define MQTT_CALLBACK_SIGNATURE void (*callback)( char *, uint8_t*, unsigned int ) |