To my surprise the following code prints 1
.
std::cout << [](const char* arg){ return arg[0]=='s'; } << std::endl;
Can someone explain this, please?
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?.
© 2022 - 2024 — McMap. All rights reserved.
bool
. – Fragmentstd::cin >> [](const char* arg){ return arg[0]=='s'; }
worked. ;) – Suck