NguyenDat
NguyenDat

Reputation: 4159

Deciphering (*(void(*)())0)()

They said this expression is valid in C, and that it means calling a function:

(*(void(*)())0)();

Can someone clearly explain what this expression means?

I tried to compile this and was surprised that it didn't result in an error.

Upvotes: 7

Views: 809

Answers (5)

dash-tom-bang
dash-tom-bang

Reputation: 17883

It's a pointer to a function at NULL.

void(*)() is the definition of a pointer to a function taking no args that doesn't return anything; you can name it:

typedef void(*my_func)();

then in your example you've got a cast:

(my_func)0 yields a function pointer to a my_func, that is, a function taking nothing and returning nothing.

Then you dereference it with the leading asterisk (which is unnecessary, afaik), and then you call it.

So you're calling a function taking no arguments and returning nothing that happens to live at address zero.

This is (usually) undefined behavior, and will crash instantly on many platforms. (It is not undefined behavior if you put a function at address zero, at least I wouldn't think it was.)

Upvotes: 3

Michael Dorgan
Michael Dorgan

Reputation: 12515

Break it down per parenthesis.

The last () signifies a function with no parameters.

The line (void(*)()) means a function that returns void.

The last little bit, the (* at the beginning and the 0) is telling the compiler that the address of the function to call lies at pointer location 0.

So basically, you are calling whatever the heck lies at address 0 with no parameters. Not usually very safe. :)

Upvotes: 2

Steve Jessop
Steve Jessop

Reputation: 279455

Step by step:

   void(*)()        // a pointer-to-function type, taking unspecified parameters
                    // and returning nothing.
  (void(*)())0      // a null pointer of that pointer-to-function type
(*(void(*)())0)     // dereference that pointer
(*(void(*)())0)();  // and call it with no parameters

The code has undefined behaviour, it'll probably crash with some kind of illegal access / segfault.

Upvotes: 19

alvin
alvin

Reputation: 1196

in an embedded environment, could be a way to call the system reset routine.

Upvotes: 2

Brian R. Bondy
Brian R. Bondy

Reputation: 347606

You are creating a pointer to a function and then calling it. I wouldn't call it a hidden feature but undefined behavior.

Basically you are doing this but with the address 0 instead:

void test() { }

void(*pfn)() = test;
(*pfn)();

Upvotes: 6

Related Questions