What does C expression ((void(*)(void))0)(); mean?

c

Solution

This is a function expecting no arguments and returning no value:

void f(void)

This is a pointer to a function expecting no arguments and returning no value:

void (*p)(void)

This is the type of that pointer:

void (*)(void) /* just remove the p! */

This is that type in parentheses:

(void (*)(void))

This is a cast to that type (the type in parentheses, followed by a value):

(void (*)(void))0

Still with me? so far we have the integer value 0 cast to a pointer-to-function-that-takes-no-arguments-and-returns-nothing.

The cast is an expression with pointer-to-function type. When you have one of those you can call it like this:

(your expression here)(arguments to the function)

The first set of parentheses are just for precedence, and sometimes might not be needed (but this time they are). The end result:

((void (*)(void))0)(/* no args */);

Takes the value 0, casts it to pointer-to-function-expecting-no-arguments-and-returning-nothing, and calls it, supply no arguments.

Problem

`((void(*)(void))0)();` So we have integer 0 type casting to this tricky type `(void(*))(void)` and then executing it. Source claims that this should work, but what does it actually? This must be one of those C jokes like `#define TRUE FALSE`, I suppose.

Original source

Related problems