3

I want to understand how a pointer to function works and how the functions are called in C.

In this example:

#include <stdio.h>

void invoked_function();

int main(void) {

     void(*function)();
     function = invoked_function;

     function();  //First way to call invoked_function
     (*function)(); //Second way to call invoked_function

     return 0;
}

void invoked_function() {
     printf("Hi, I'm the invoked function\n\n");
}

I call the function invoked_function using function(); and (*function)();, both work actually.

If the first one contanis the memory address of invoked_function, and the second contains the first byte of the code of invoked_function, why are working both?

  • 2
    Because the language is constructed this way. – 0___________ Sep 03 '17 at 10:19
  • Instead of writing a novel with code-snippets, provide a [mcve]. – too honest for this site Sep 03 '17 at 11:25
  • edited !!! Thanks –  Sep 03 '17 at 12:02
  • "the second contains the first byte of the code of `invoked_function`". No. That would be true if `function` were a pointer-to-char. But it's not, it's a pointer-to-*function*. So `function` is the pointer, and `*function` is the function, and `(*function)()` is the logical way to call it. But since there's not much you can do with a function pointer except call it, when you write `function()`, without the `*`, the compiler (for once in its tiny, narrow-minded life) says, "Oh, okay, I guess you're trying to call the pointed-to function, so that's what we'll do." – Steve Summit Sep 03 '17 at 17:14
  • Nice dude, well done that's the answer –  Sep 04 '17 at 07:24

1 Answers1

4

This:

function = invoked_function;

is equivalent to this:

function = &invoked_function;

since the first is also valid since the standard says that a function name in this context is converted to the address of the function.

This:

(*function)();

is the way to use the function (since it's a function pointer).

However, notice that:

function()

is also accepted, as you can see here.

There is no black magic behind this, C is constructed like this, and function pointers are meant to be used like this, that's the syntax.

gsamaras
  • 71,951
  • 46
  • 188
  • 305