I am working through Jack Purdum’s book on programming C for the Arduino. The following code appears in Chapter 9.
void setup() {
Serial.begin(9600); // Serial link to PC
}
void loop() {
int number = 50;
int (*funcPtr)(int n); // This defines a pointer to function
funcPtr = DisplayValue; // This copies the lvalue of DisplayValue
number = (*funcPtr)(number);
Serial.print("After return from function, number = ");
Serial.println(number);
Serial.flush();
exit(0);
}
int DisplayValue(int val) //I don’t understand this statement.<<<<<<<<<<<<<
{
Serial.print("In function, val = ");
Serial.println(val);
return val * val;
}
This program runs fine but I do not understand the placement or the syntax of the statement indicate by the <<<<<<<<< above. Why no semicolon terminator? How does program know what “DisplayValue” is in Loop()?
DisplayValue() is a separate function, just like loop() is. You can create multiple functions in a program.
Specifically DisplayValue() is a function with one argument, a signed integer called “val” and it returns a signed integer. There’s no semicolon after the close paren since that’s not the end of the function, the closing bracket is.
This example is using a function pointer to call DisplayValue(). Most of the time, you don’t use function pointers, and would call the function directly:
number = DisplayValue(number);
In this case, you have a pointer to the function (the linker will fill it in automatically), and you use that to call it.
Function pointers are a more specialized case; you find them in callback routines, menus, task switchers, and other places where you want the code to call one of many functions based on some variable or choice.
The answer above is correct and if you had kept the indentation of the code it would be more obvious. I formatted the code and added some comments below.
void setup() {
Serial.begin(9600); // Serial link to PC
} // this brace indicates the setup() ends here
void loop() {
int number = 50;
int (*funcPtr)(int n); // This defines a pointer to function
funcPtr = DisplayValue; // This copies the lvalue of DisplayValue
number = (*funcPtr)(number);
Serial.print("After return from function, number = ");
Serial.println(number);
Serial.flush();
exit(0);
} // this brace indicates the loop() ends here
int DisplayValue(int val) //I don't understand this statement.<<<<<<<<<<<<<
{
Serial.print("In function, val = ");
Serial.println(val);
return val * val;
}