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;
}
First, let’s use cdecl to explain the inner gibberish:
So
(void (*)()) stringcastsstringinto a function pointer. Then the function pointer is dereferenced to call the underlying function. The line is equivalent toThis (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
cdecltool can be useful to understand or write complicated C types and declarations.