I have this code:
void longitudeChanged() {
Serial.println("Longitude: " + String(GpsLon.value,8));
}
in main:
GpsLon.onUpdate(longitudeChanged);
I would like to do something like this:
GpsLon.onUpdate({
Serial.println("Longitude: " + String(GpsLon.value,8));
});
(Like I do in Java script!); but this is not the rigth way. How to do it?
Tnx
Erik
Till now, we have seen that in C programming, we can pass the variables as an argument to a function. We cannot pass the function as an argument to another function. But we can pass the reference of a function as a parameter by using a function pointer.
Function Call When calling a function with a function parameter, the value passed must be a pointer to a function. Use the function's name (without parentheses) for this: func(print); would call func , passing the print function to it.
The values that are declared within a function when the function is called are known as an argument. These values are considered as the root of the function that needs the arguments while execution, and it is also known as Actual arguments or Actual Parameters.
When one piece of code invokes or calls a function, it is done by the following syntax: variable = function_name ( args, ...); The function name must match exactly the name of the function in the function prototype. The args are a list of values (or variables containing values) that are "passed" into the function.
Behold, the mighty lambda!
#include <iostream>
template <typename T>
void myFunction(T t) {
t();
}
int main() {
myFunction([](){ std::cout << "Hi!" << std::endl; });
}
If you'd like to learn more about them, take a look here
To decrypt this a little, here's a breakdown:
[]
(the capture, don't worry too much about that for now) ()
the function arguments, in this case there are none) and { ... }
(the body, just like any other function).So the lambda part is just this:
[](){ std::cout << "Hi!" << std::endl; }
Here's another example of a lambda that takes an int and returns double its value:
[](int value){ return value * 2; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With