Caiyi Zhou
Caiyi Zhou

Reputation: 141

Why this C++ lambda funtion returns 1?

I have a lambda function as below, it explicitly declares int as its return type, but in its realization, it does nothing. Besides, it prints out its return value. To my surprise, it compiles without error and returns 1. Who knows the reason?

auto lambda = [](int a) -> int{};
cout << lambda << endl;

Upvotes: 1

Views: 166

Answers (1)

songyuanyao
songyuanyao

Reputation: 172884

I print out its return value

No. You're printing out the lambda itself. For this case it converts to function pointer, then converts to bool implicitly. For non-null pointer the converted result is true (i.e. 1 in this case. You can use std::boolalpha to get the print result as true or false like cout << boolalpha<< lambda << endl;).

If you want to print out the return value of the lambda, it should be

cout << lambda(42) << endl;

but note that flowing off the end of a value-returning function (except main) without a return statement is undefined behavior, this is true for lambdas too.


BTW: Only lambdas without captures can convert to function pointer implicitly, while lambdas with captures can't.

Upvotes: 11

Related Questions