Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is passing additional parameters through function pointer legal/defined in C? [duplicate]

Possible Duplicate:
Casting a function pointer to another type

Assume i initialize a function pointer with a function that actually takes less parameters then the function pointer definition, will the function still perform correctly if called through the function pointer?

I tried this with gcc and it worked as expected, but i wonder if that behaviour is consistent across compilers/platforms (i suspect in some enviroments it might wreak havoc on the stack):

#include <stdio.h>

typedef void (*myfun)(int, int, int);

void test_a(int x, int y, int z) {
    printf("test_a %d %d %d\n", x, y, z);
}

void test_b(int x, int y) {
    printf("test_b %d %d\n", x, y);
}

int main() {
    myfun fp;
    fp = test_a;
    fp(1, 2, 3);
    fp = (myfun) test_b;
    fp(4, 5, 6);
}
like image 497
Askaga Avatar asked Nov 18 '12 21:11

Askaga


People also ask

Which is the correct way to pass a Function Pointer to arguments?

We cannot pass the function as an argument to another function. But we can pass the reference of a function as a parameter by using a function pointer. This process is known as call by reference as the function parameter is passed as a pointer that holds the address of arguments.

Can you pass functions as parameters in C?

In C programming you can only pass variables as parameter to function. You cannot pass function to another function as parameter. But, you can pass function reference to another function using function pointers.

Can we have a pointer to a function?

A pointer to a function points to the address of the executable code of the function. You can use pointers to call functions and to pass functions as arguments to other functions. You cannot perform pointer arithmetic on pointers to functions.


2 Answers

It is undefined behavior. Use at your own risk. It has been rumored to cause Nasal Demons!

enter image description here

like image 188
EvilTeach Avatar answered Sep 22 '22 23:09

EvilTeach


The behavior of your program is undefined. The fact that it compiles at all is because of the cast, which effectively tells the compiler "this is wrong, but do it anyway". If you remove the cast, you'll get the appropriate error message:

a.c:17:8: error: assignment from incompatible pointer type [-Werror]

(From gcc -Wall -Werror.)

More specifically, the behavior depends on the calling conventions. If you were on a platform were the arguments were passed in "reverse" order on the stack, the program would give a very different result.

like image 33
Fred Foo Avatar answered Sep 20 '22 23:09

Fred Foo