2

I was writing simple C++ program, while using lambda function, and I got into this situation

std::cout << [](int x = 10) -> int { return (x + 5); } << std::endl; // prints 1

I expected, with no passing argument, this lambda function would return 15, therefore printed result would be 15.

But above lambda function returns 1 instead. Does it mean that the lambda function just worked correctly? Is is some kind of flag value?

Hashnut
  • 367
  • 3
  • 18
  • 12
    The Lambda is not being called and is decaying to a pointer which is printed as 1 if not null and 0 if null. Change it to `[](int x = 10) -> int { return (x + 5); }()` to call it. – Richard Critten Jan 12 '22 at 00:02
  • 2
    @RichardCritten Why is the pointer printing as 1 or 0 though? An ordinary `int*` pointer prints in hexadecimal (so an output of the form `0x768ab3` would make sense to me), so why do lambdas decay to Boolean when printed? – Silvio Mayolo Jan 12 '22 at 00:09
  • 4
    @SilvioMayolo _"...There are no overloads for pointers to non-static members, pointers to volatiles, (until C++23) or __function pointers__ (other than the ones with signatures accepted by the (11-13) overloads). Attempting to output such objects invokes __implicit conversion to bool__, and, for any non-null pointer value, the value 1 is printed (unless boolalpha was set, in which case true is printed)...."_ see __Notes__ here - [std::basic_ostream::operator<<](https://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt) – Richard Critten Jan 12 '22 at 00:51
  • See also https://stackoverflow.com/questions/2064692/how-to-print-function-pointers-with-cout – Drew Dormann Jan 12 '22 at 01:02

0 Answers0