Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any distinction between using function or pointer to function notation?

Consider the following program:

#include <stdio.h>

void f() {}
void g1(void fun(void)) { printf("%p\n", &fun); }
void g2(void (*fun)(void)) { printf("%p\n", fun); }

int main(void) {
    g1(f);
    g2(&f);
    printf("%p\n", &f);
    return 0;
}

As C11 does not have lambda expressions, there is no way a literal function could be passed as parameter to g1 or g2, so in a way, these two functions do the same thing(you must define the parameters first); I'm reading a book right now that says that

The fact that technically this function (f) is passed on as a function pointer (to g1) is usually of minor interest, [...]

So, what I understand is that the writer is saying that both semantically are equivalent.

But the addresses that get printed when calling g1 and g2 are different, where g2 outputs the real address of f. This means that g1 makes a copy of f, meaning that f is passed by value. Is the book wrong or am I? I don't think the book is wrong, but the addresses are different and certainly it matters which one you choose. And if there are any distinctions, which one should be prefered in what scenario?

like image 710
Garmekain Avatar asked Feb 18 '26 22:02

Garmekain


1 Answers

You are very wrong.

Whenever you think you pass a function to a function, you are actually passing a pointer to it.
Whenever a function Looks like it has a function-parameter, it actually has a function-pointer-parameter.

Now, in one of your functions you print the value of a pointer to the argument, in the other the argument. Aside from the fact that %p is for void* not for other data-pointers and especially not for function-pointers, which means you have Undefined Behavior, there is every reason to expect them to be different, especially on an architecture with a shared address space for data and instructions.

like image 62
Deduplicator Avatar answered Feb 20 '26 13:02

Deduplicator



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!