2

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
}
Donald Duck
  • 8,409
  • 22
  • 75
  • 99
  • Don't know javascript but it seems similar to function pointers in c – Support Ukraine Jul 11 '16 at 12:02
  • Not quite. Anonymous functions are a little more than just that. They can capture their context (i.e. they can be defined on the spot -- like above) and can capture the local variables of the (outer) function in which they are defined. – Rudy Velthuis Jul 11 '16 at 12:28

3 Answers3

7

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
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • Not really equivalent, indeed, because this can not be defined inline (inside another function). Anonymous functions can even capture the local variables of the outer function, etc. – Rudy Velthuis Jul 11 '16 at 12:26
  • FWIW, Delphi is a static language too, but it can do anonymous functions. The real problem is that C is a procedural and not an OO language. +1 anyway. – Rudy Velthuis Jul 11 '16 at 12:31
2

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.

Community
  • 1
  • 1
0

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:

  • Init function pointer fp1 with a reference to a()
  • Call fp1
  • Overwrite function pointer with a reference to b()
  • Call fp1
Christian Ammann
  • 888
  • 8
  • 19