Playing around with dynamic C. I want to be able to reassign functions to different functions at runtime. I came up with the following. I’m not comfortable that this is the best approach, but it was odd enough that I thought I would post it:
#include <stdio.h> void sayHello(){ printf("%s\n", "Hello!"); } void sayBye(){ printf("%s\n", "Bye!"); } void saySomething(const char * c){ printf("Going to say: %s\n", c); } void sayNothing(){ printf("I refuse to say anything\n"); } int main (int argc, const char * argv[]) { //the greeting function pointer void (*greeting)(void); //assign greeting to the sayHello function greeting = sayHello; greeting(); //assign greeting to the sayBye function greeting = sayBye; greeting(); //the function pointer for saySomething and sayNothing void (*fncPtr)(const char *); fncPtr = saySomething; fncPtr("Something is being said"); //Very confused by this. At this point fncPtr is a variable AND a function pointer. //By just assigning it the signature as the function sayNothing, it will not compile //because it's a variable and needs a variable assigned to it. //I assign it the value of NULL (\0) after the function signature of sayNothing, //which compiles (anything, such as an int could also be assigned). //I then can assign fncPtr to the void argument function sayNothing. //At this point, however, it will will not compile. I have to "pretend" it hass the //same arguments as it was originally assigned, however, //it will instead run the sayNothing(void) function at runtime even though I'm passing //in the const char * "this means nothing". //I think a lot of the oddness has to do with formating the code to pass through the //compiler, while at runtime it's a different story. fncPtr = (void (*)())'\0'; fncPtr = sayNothing; fncPtr("this is a useless argument"); return 0; }