To my surprise the following code prints 1
.
std::cout << [](const char* arg){ return arg[0]=='s'; } << std::endl;
Can someone explain this, please?
It's converting to a function pointer, and then through that to a bool:
void foo ();
std::cout << &foo << std::endl;
Prints the same thing, and the same warnings; I happened to compile with gcc set to 17 standard and I saw:
main.cpp:6:56: warning: the address of 'static constexpr bool main()::<lambda(const char*)>::_FUN(const char*)' will never be NULL [-Waddress]
std::cout << [](const char* arg){ return arg[0]=='s'; } << std::endl;
With the code above you see the same warning.
To add on a bit to my answer: there is a stream overload for void*
. However, function pointers, unlike pointers to data, cannot implicitly convert to void*
. The only implicit conversion for function pointers is boolean, and of course there is a stream operation for bool, so that overload is selected and that implicit conversion occurs. See: How to print function pointers with cout?.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With