4

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?

3
  • 2
    Because the language is constructed this way. Commented Sep 3, 2017 at 10:19
  • Instead of writing a novel with code-snippets, provide a minimal reproducible example. Commented Sep 3, 2017 at 11:25
  • "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." Commented Sep 3, 2017 at 17:14

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.