What does the value from dereferencing a function pointer means

Viewed 149
#include <iostream>

void PrintTheValue(int(*func)(int a));

int main(int argc, char **argv) {
    PrintTheValue([](int a) {return a; });
    
    return 0;
}

void PrintTheValue(int(*func)(int a)) {
    std::cout << *func << std::endl;
}

In my concept of understanding the func, it would be a pointer to an int passed by value. But in this case I'm passing a lambda which doesn't seem to be called anywhere. (So there isn't any value at all?)

When I run this, it doesn't break the program, but instead printed 00EE6F80.

What does this address mean? I have no idea how to interpret it.

2 Answers

In my concept of understanding the func, it would be a pointer to an int passed by value.

func is a pointer to function, which takes an int and returns int.

But in this case I'm passing a lambda which doesn't seem to be called anywhere.

You're passing a lambda without capturing, which could convert to pointer to function implicitly. In PrintTheValue, *func, i.e dereference on the pointer results in a reference to function, and for being passed to operator<< of std::cout, it converts to function pointer again, then converts to bool with value true (as a non-null pointer), then you should get the result 1 (or true with the usage of std::boolalpha). If you want to call on func you could func(42) (or (*func)(42)).

A lambda is an unnamed function object of the closure type. The crucial part for this case, this class does not overload the operator<<.

When you dereference the passed lambda in *func, there is no overload for operator<<, so it converts to nearest acceptable result which is bool (at first it reverts to a regular pointer).

The documentation:

Dereferencing a function pointer yields the lvalue identifying the pointed-to function

int f();
int (*p)() = f;  // pointer p is pointing to f
(*p)();          // function f invoked through the function lvalue
// But no sense in *p

It should print 1 (since non-null pointer), which it does for me (g++). The language does allow us to do so, but there's no sense in dereferencing a pointer to function without calling the function. All the peculiarities of the function pointers are due to that they have one reasonable usage, so anything you do with them will support that usage - @Pete Becker

For more on Function Pointers check here, it will aid.

Related