Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Complicated C cast explanation

Tags:

c

casting

void

I'm trying to figure out what the following code in C does?

((void(*)())buf)();

where 'buf' is a char array.

like image 831
Tony The Lion Avatar asked Nov 11 '09 14:11

Tony The Lion


2 Answers

Let's take it one step at a time.

void(*)()

This is a pointer to a function that takes unspecified arguments and has no return value.

(void(*)())buf

simply casts buf to this function pointer type. Finally,

((void(*)())buf)();

calls this function.

So the entire statement is "interpret buf as a pointer to a void function without arguments, and call that function."

like image 120
Thomas Avatar answered Oct 27 '22 14:10

Thomas


It casts buf to a function pointer of type void(*)() (A function returning nothing/void and taking unspecified arguments) and calls it.

The ANSI standard does not really allow the casting of normal data pointers to function pointers, but your platform may allow it.

like image 30
Wernsey Avatar answered Oct 27 '22 12:10

Wernsey