33

Possible Duplicate:
How does dereferencing of a function pointer happen?

  void myprint(char* x) {
      printf("%s\n", x); 
  }

  int main() {
     char* s = "hello";
     void (*test)(char*);
     void (*test2)(char*);

     test = myprint;
     test2 = &myprint;

     test(s);
     (*test)(s);
     test2(s);
     (*test2)(s);

  }

Can anyone explain to me why all of the above code is valid? "hello" is printed four times. By applying the function pointer, is it implicitly derefenced? Basically I want to know how function pointers are actually stored, because the above is kind of confusing.

Community
  • 1
  • 1
Sean Nilan
  • 1,745
  • 1
  • 14
  • 21
  • 1
    `(******test)(s)` is also valid :-) – sidyll Sep 22 '11 at 17:22
  • 1
    See this previous question: http://stackoverflow.com/questions/2795575/how-does-dereferencing-of-a-function-pointer-happen – Judah Jacobson Sep 22 '11 at 17:24
  • 1
    Functions and function pointers are special, their treatment in not uniform with any other kind of pointer. See [How does dereferencing of a function pointer happen?](http://stackoverflow.com/q/2795575/2509) and other questions in the sidebar. – dmckee --- ex-moderator kitten Sep 22 '11 at 17:24

1 Answers1

62

This is just a quirk of C. There's no other reason but the C standard just says that dereferencing or taking the address of a function just evaluates to a pointer to that function, and dereferencing a function pointer just evaluates back to the function pointer.

This behavior is (thus obviously) very different from how the unary & and * operators works for normal variables.

So,

test2 = myprint;
test2 = &myprint;
test2 = *myprint;
test2 = **********myprint;

All just do exactly the same, gives you a function pointer to myprint

Similarly,

test2(s);
(*test2)(s);
(***********test2)(s);

Does the same, call the function pointer stored in test2. Because C says it does.

nos
  • 223,662
  • 58
  • 417
  • 506