Pointers to function

And for anyone that hasn't seen it done recently:

// Generic arithmetic funtion
typedef int (*GeneralFunction) (const int arg1, const int arg2);

int Add (const int arg1, const int arg2)
{
 return arg1 + arg2; 
} // end of Add

int Subtract (const int arg1, const int arg2)
{
 return arg1 - arg2; 
} // end of Subtract

int Divide (const int arg1, const int arg2)
{
 return arg1 / arg2; 
} // end of Divide

int Multiply (const int arg1, const int arg2)
{
 return arg1 * arg2; 
} // end of Multiply

void setup ()
{
 // make pointers to functions, put them in local variables
  GeneralFunction fAdd = Add;
  GeneralFunction fSubtract = Subtract;
  GeneralFunction fDivide = Divide;
  GeneralFunction fMultiply = Multiply;
  
  Serial.begin (115200);
  Serial.println ();
  
  //  use the function pointers
  Serial.println (fAdd (40, 2));
  Serial.println (fSubtract (40, 2));
  Serial.println (fDivide (40, 2));
  Serial.println (fMultiply (40, 2));
}  // end of setup

void loop () {}

Output:

42
38
20
80

Function pointers are useful for generic things (eg. do to everything in an array). Also for callbacks. That is, you might want to do on an interrupt.

2 Likes