Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does casting a function actually work in C?

int foo(char *c)  {...}

main() {
     int (*thud)(void *);

     thud = (int (*)(void *))(foo);
}

What actually happens during the evaluation of the assignment?

There is a difference between the cast type and foo; the cast type is a pointer and foo is a function. So, does the compiler convert what's in '(foo)' into a pointer to foo and only then make the cast? Because nothing else seems to make sense; the other option is that the function itself is converted to a pointer to a function that gets a void* and returns an int, and as far as I know a function is a label to a piece of code in memory and thus cannot become a pointer, which is a variable.

like image 467
Ori Popowski Avatar asked Apr 16 '09 18:04

Ori Popowski


1 Answers

The name of a function is a pointer when used as such. It's somewhat similar to how the name of an array is a pointer to its first element.

That being said, calling a function through a pointer with a different type than the function's actual prototype (as your example does) is undefined behavior. Don't do it.

Addendum

If a converted pointer is used to call a function whose type is not compatible with the pointed-to type, the behavior is undefined.

from section 6.3.2.3 of the C standard.

like image 170
ephemient Avatar answered Sep 19 '22 01:09

ephemient