I'm trying to figure out what the following code in C does?
((void(*)())buf)();
where 'buf' is a char
array.
I'm trying to figure out what the following code in C does?
((void(*)())buf)();
where 'buf' is a char
array.
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.
I would guess that in many circumstances, it crashes the machine. Otherwise, it treats the array as a pointer to a function that returns void and invokes it.
It casts buf
into a function pointer, that takes unspecified arguments, and calls it.
This casts buf
to the type void (*)()
, a pointer to a function that takes unspecified parameters and returns nothing. Then it calls the function at that address (the two rightmost parentheses).
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."
((void(*)())buf)(); \------------/ cast `buf` to \---------/ type: pointer to function accepting a fixed but unspecified number of arguments and returning void \----------------/ and call that "function"
You might find "expert c programming" a good read - unpacking this kind of thing is in one of the chapters, if I remember right. It's a long time since I read it, but I remember thinking it was worth the effort at the time. http://www.amazon.com/Expert-Programming-Peter-van-Linden/dp/0131774298
I tend to use the "cdecl" command when I come across a mind boggling declaration. Example:
[me@machine]$ cdecl
Type `help' or `?' for help
cdecl> explain (void(*)())buf
cast buf into pointer to function returning void
Although there are cases where I do wish that there's a tool out there that explains the output of "cdecl" :/
There is an online version of the 'cdecl' tool that lsc mentioned that you might find useful : http://www.cdecl.org/