user8554358
user8554358

Reputation:

Invoke function using pointer to function in C

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?

Upvotes: 4

Views: 2450

Answers (1)

gsamaras
gsamaras

Reputation: 73444

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.

Upvotes: 5

Related Questions