Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this allowed to call functions with different prototypes by a pseudo-generic function pointer?

Assuming that all functions share the same return type, is it valid to call each one by a "generic" function pointer, that is declared with empty parentheses (so it does not specify its arguments)?

Here is an example code, that illustrates it:

#include <stdio.h>

void fun1(void)
{
    printf("fun1\n");   
}

void fun2(int a)
{
    printf("fun2: %d\n", a);
}

void fun3(int a, int b)
{
     printf("fun3: %d %d\n", a, b);
}

int main(void)
{
    void (*pf)(); // pseudo-generic function pointer

    pf = fun1;
    pf();

    pf = fun2;
    pf(0);

    pf = fun3;
    pf(1, 2);

    return 0;
}
like image 915
Grzegorz Szpetkowski Avatar asked Jun 04 '16 16:06

Grzegorz Szpetkowski


1 Answers

You may do similar stuff, but not exactly that way. When you call a function through a function pointer you have to be sure that the prototype on the calling side is exactly as the function was defined.

Now a function declarations with empty parenthesis isn't even a prototype, so this is not the right way to call it. The main reason is that the calling convention might be slightly different than you'd expect. For () functions special rules apply, namely narrow types are converted to int, unsigned or double.

Now what you may do is store a function pointer in pf as you do, but then you'd always have to convert it back to the correct function pointer before the call, such as

((void (*)(int, int))pf)(a, b);

This is barely readable and much errorprone. You should avoid such gymnastics as much as you can.

like image 82
Jens Gustedt Avatar answered Sep 19 '22 12:09

Jens Gustedt