Function pointer array with immediate initalization with nameless functions
What I'm trying to do is make an array of functions, and initialize it with "anonymous" functions. That is, the function is only defined inside of the array. I currently use an enum to simulate calling the function by name but you could just as well call it with functions[0]. But I can't figure out the syntax: the compiler says "error: ‘i’ undeclared (first use in this function)".
Code:
#include <stdio.h>
#include <stdlib.h>
#define break_code
int print_add(int i){
printf("%d\n", ++i);
return i;
}
int main(int argc, char const *argv[])
{
enum {printadd=0};
int (*functions[1])(int i) = {
#ifdef break_code
(int(*)(int i)){
printf("%d\n", ++i);
return i;
}
#endif
};
#ifndef break_code
functions[printadd] = print_add;
#endif
// b will be 6
int b = functions[printadd](5);
return 0;
}
In javascript, this would be something like
Code:
functions = { print_add: function(i){i++; console.log(i); return i;} };