Reputation: 25
To call a function by just a name, I've came up with this piece of code. This currently works, but I'm not sure if it is undefined behavior. Could anyone shed some light on this and maybe help me come up with a better solution.
#include <stdio.h>
typedef void (*FunctionCallback)();
void first(char *str);
void second(int , int);
FunctionCallback function[] = {&first, &second};
void first(char *str )
{
printf( "First: %s\n", str );
}
void second(int x, int y)
{
int answer;
answer = x +y;
printf("Second: %d\n", answer);
}
int main()
{
function[0]("Working");
function[1](6, 5);
return 0;
}
Upvotes: 1
Views: 86
Reputation: 1920
This should be ok, if you are careful. I think UB might be only in case of first
, which expects char*
, but is has const char*
passed to it. Perhaps on some platform, the compiler puts the const char*
stuff into some weirds place, and writable memory is addressed differently. But that is exotic, hypothetic.
Anyways, to be clear, in C:
typedef void (*FunctionCallback)();
is a type of pointer to a function with no argument list. So it is compatible, as mafso said it.
typedef void (*FunctionCallback)(void);
would mean a pointer to a function that expects zero arguments. This would only be compatible with other functions taking zero arguments. ( Note it differs from C++, where fun()
is the same as fun(void)
in C )
EDIT:
I would emphasise more, that one still needs to get the arguments right, each time. Meanwhile, the compiler can't help you with that, so, hm, good luck with that.
I can imagine a compiler, that wants to be clever, sees you never ever store the address of any fun(const char*)
, and use this to optimize your code, thus removing the call to first
.
Upvotes: 1
Reputation: 5543
The code is valid, but makes use of old-style declarations, which have been marked obsolescent in C89. The function pointer used to call a function and the function called must be of compatible type and the types of the parameters passed must match those of the definition. Both is true for the code shown.
Note, that this technique doesn't work for variadic functions or functions with an argument which isn't "self-promoting", for example of type short
or float
.
Upvotes: 0