what is the difference between declaring a lambda as constexpr vrs returning constexpr?

What is the difference between these 2 lambdas?

1
2
3
4
5
6
7
8
9
10
auto squared4 = [](auto val) constexpr
{
	return  val * val;
};

constexpr auto squared5 = [](auto val)
{
	return  val * val;
};


Regards,
Juan
in the first case, operator() on the lambda is explicitly marked as a constexpr function. This is redundant because lambda operator()s are automatically constexpr if they can be.

in the second case, the lambda's operator() is auto-constexpr as always, and the variable "squared5" is a constexpr variable, which also makes it a const variable, so we can contrive a difference:
1
2
3
4
5
int main()
{
  squared4 = decltype(squared4){}; // OK: can be reassigned
// squared5 = decltype(squared5){}; // Error: const (because of constexpr)
}
Last edited on
but this code you provide does not compile and it does something very strange (the assignment of a lambda object into a lambda function...)
In c++20, lambdas can be default-constructed if they capture nothing.
See the cppreference page (that Cubbi probably wrote):
https://en.cppreference.com/w/cpp/language/lambda
this code you provide does not compile

does too: https://wandbox.org/permlink/vkAhYZnCtZC1MudP
Registered users can post here. Sign in or register to post.