What's an idiomatic way of specifying an optional callback in C? I have a long running function that waits for a radio packet by constantly polling Arduino hardware, and I want to have the option of specifying an optional callback to be called after every time it polls the hardware and fails to read the packet. Here's the skeleton function definition:
typedef void(*waitCallback)(const unsigned long elapsed);
bool readPacket(unsigned long timeout, waitCallback cb) {
long time = millis();
unsigned long delta = 0;
while(delta < timeout) {
if(receivedPacket()) {
return true;
}
delta = millis() - time;
cb(delta);
}
return false;
}
My question is, how can I make the callback optional? I could make a dummy function without a body and specify that as a callback if I don't want any callback, but is there a cleaner way to do this?
In this case you could use two methods, not so clean neither elegant but works for this.
Method one: pass NULL and check it inside.
bool readPacket(unsigned long timeout, waitCallback cb) {
long time = millis();
unsigned long delta = 0;
while(delta < timeout) {
if(receivedPacket()) {
return true;
}
delta = millis() - time;
if(cb!=null){
cb(delta);
}
}
return false;
}
Method two: defining a function without parameter. It use the method one implicitly.
bool readPacket(unsigned long timeout){
return readPacket(timeout, NULL);
}
Using second method you could make some generic functions that match with other specifications. You could pass other type of parameters and implictly cast them, add other parameters to make a preprocess, check errors...
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