tags:

views:

89

answers:

2

What's happening in this code? I don't get this code. Looks like it's performing some type of casting or using function pointers but I'm not sure. Will appreciate if someone can help me. Thanks.

const char string[]="Hello!";

int main()   
{

    (*(void (*)()) string)(); //Obviously, my problem is this line :)

    return 0;
}
+3  A: 

void (*)() is a function pointer type. (void (*)()) string casts string to such a function pointer. The remaining (* ...)() in the expression dereferences this resulting function pointer and tries to call the function.

Since there isn't any function where that pointer points to, but only the string "Hello!", this won't lead to any useful results.

sth
Thanks! It really helped me.
Naruto
+4  A: 

First, let's use cdecl to explain the inner gibberish:

$ cdecl
cdecl> explain (void (*)())
cast unknown_name into pointer to function returning void

So (void (*)()) string casts string into a function pointer. Then the function pointer is dereferenced to call the underlying function. The line is equivalent to

void (*fp)() = (*(void (*)()) string)();
(*fp)();

This (on most machines) tries to execute "Hello!" as machine code. It may crash outright on machines with virtual memory because data is often marked as non-executable. If it doesn't crash, it's not likely to do anything coherent. In any case, this is not useful code.

The only thing to learn here is that the cdecl tool can be useful to understand or write complicated C types and declarations.

Gilles
+1 for introducing me to cdecl.org! What a fantastic little service!
A. Levy
Thanks! It really helped me.Also, thanks for introducing me too to cdecl.
Naruto