I would like to know if there is an equivalent in C (for a void
function) to this javascript code:
var myFunction;
myFunction = function(){
//Some code
}
I would like to know if there is an equivalent in C (for a void
function) to this javascript code:
var myFunction;
myFunction = function(){
//Some code
}
Not really equivalent (because C is a static language without support for anonymous or nested functions) but you can have a variable that is a pointer to a function, and make it point to different compiled functions matching the type of the variable.
Very simple and basic example:
#include <stdio.h>
void function1(void)
{
printf("function1\n");
}
void function2(void)
{
printf("function2\n");
}
int main(void)
{
// Declare a variable that is a pointer to a function taking no arguments
// and returning nothing
void (*ptr_to_fun)(void);
ptr_to_fun = &function2;
ptr_to_fun();
ptr_to_fun = &function1;
ptr_to_fun();
return 0;
}
The above program will print out
function2 function1
In C you can use a function pointer:
void the_function(void) {
// ...
}
void (*my_function)(void) = the_function;
C doesn't support anonymous functions so your function needs to have a name by itself (here I use the_function
).
You call the function via function pointer like you'd call an ordinary function:
my_function();
However this practice is subject to limitations. First of all, you must know the number and the type of arguments that the function expects. Calling it with wrong arguments will invoke undefined behaviour. Also, you need to know the actual type of return value as well. And these need to be known at compile-time. You need to use tricks like libffi
to call a function whose signature you do not know at runtime.
If you want to change the behaviour of a certain function call, you could operate on a function pointer instead of calling the function directly: