I wonder why this lambda function doesn't return the right answer:
int main()
{
int a = 3, b = 7;
[&]() ->void {(&a == &b) ? a : (a ^= b, b ^= a, a ^= b); };
std::cout << a << " " << b;
return 0;
}
It shows me 3 7 instead of 7 3
I wonder why this lambda function doesn't return the right answer:
int main()
{
int a = 3, b = 7;
[&]() ->void {(&a == &b) ? a : (a ^= b, b ^= a, a ^= b); };
std::cout << a << " " << b;
return 0;
}
It shows me 3 7 instead of 7 3
You didn't call the lambda. You just declared an unnamed function object which is discarded immediately. You can call it as
[&]() ->void {(&a == &b) ? a : (a ^= b, b ^= a, a ^= b); } ();
// ^^
Then the function body will be evaluated and do what you expect.
Defining a lambda does not implicitely call it.
You have to call it:
auto f = [&]() ->void {(&a == &b) ? a : (a ^= b, b ^= a, a ^= b); };
f();