In some library code, there's a pattern of setting up callbacks for events, where the callback may receive an argument. The callback itself may not do anything with the argument, or the argument might be 0
, but it is passed. Decomposing it down to the basics, it looks like the following:
#include <stdio.h>
#include <string.h>
void callback_1(char *data) {
printf("Length of data: %d\n", strlen(data));
}
void callback_2() {
printf("No parameters used\n");
}
typedef void (*Callback)(char *);
int main(void) {
Callback callback;
callback = callback_1;
callback("test");
callback = callback_2;
callback("test");
return 0;
}
This compiles and runs on GCC 4.9.3 (32-bit) without anything unexpected.
A good callback function has a signature like callback_1, but occasionally I forget the data
parameter if it's not being used. While I'm aware that C isn't always typesafe (especially with regards to void pointers), I expected a warning, since if I had provided a mismatched parameter, e.g. int data
, I would receive a warning about incompatible types. If the typedef for Callback
didn't accept a parameter, I would receive a compilation error if a callback function had one in the signature.
Is there a way in C to get a warning for the case where a function pointer is assigned to a function where the signature is missing an argument? What happens on the stack if the callback is missing the parameter? Are there possible repercussions of missing the parameter in the callback?