Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the value from dereferencing a function pointer means

#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.

like image 441
IKnowHowBitcoinWorks Avatar asked Jan 25 '23 08:01

IKnowHowBitcoinWorks


1 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)).

like image 175
songyuanyao Avatar answered Jan 26 '23 22:01

songyuanyao