Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lambda returns '1' all time

Have code like this

#include <iostream>
using namespace std;
int main() 
{ 
  cout<<[](){ return 0;};
  cout<<[](){ return 3.2;};
  cout<<[](){ return true;};
  cout<<[](){ return false;};
  cout<<[](){ return "Hello world!";};
  cout<<[]()->int{ return 0;};
  cout<<[]()->double{ return 3.2;};
  cout<<[]()->bool{ return true;};
  cout<<[]()->bool{ return false;};
  cout<<[]()->const char*{ return "Hello world!";};
  return 0;
}

Compile it with gcc version 4.8.2 and my output is only 1111111111. Why only "1"?

like image 516
Stepan Loginov Avatar asked Feb 02 '15 08:02

Stepan Loginov


1 Answers

When a lambda expression has no capture, it is implicitly convertible to a function pointer.

A function pointer, in turn, is implicitly convertible to bool, yielding true if the pointer is not null, which gets printed.

If you cout << std::boolalpha before your outputs, you'll see truetruetrue.... printed instead.

If you capture something in your lambda, then it is no longer convertible to a function pointer, and you'd get a compiler error.

If you want to print the result returned by calling the lambda, then you need (), as others have pointed out.

like image 99
T.C. Avatar answered Sep 28 '22 08:09

T.C.