1

Since C++17 it is possible to use a lambda expression in a constexpr function.

In the related document Wording for constexpr lambda this code example is shown:

constexpr int AddEleven(int n) {
    return [n] { return n + 11; }();
}

Is this just a toy example to demonstrate the language feature, or is there an actual use case where this code has a different behaviour than the following code?

constexpr int AddEleven(int n) {
    return n + 11;
}

What would be the benefit of using a lambda expression in this case?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • I haven't followed recent developments in the language, so I'm not intimately familiar with `constexpr` or lambdas. But my immediate reaction is that if these two versions of the function behave differently, there's something seriously wrong. – Pete Becker Sep 07 '20 at 12:34

3 Answers3

1

What would be the benefit of using a lambda expression in this case?

There's no benefit.

It's simple and obvious what it does, which serves the purpose of being an example of valid code. In much the same way no-one needs a program that outputs "Hello World" to a console, but there are hundreds of uses of that in example code.

Caleth
  • 52,200
  • 2
  • 44
  • 75
1

Immediately-invoked lambdas are useful to provide a statement-friendly scope within an expression, typically to initialize const variables in a more complex way than constructor parameters permit:

auto const v = [&] {
    std::vector<int> v;

    // do some stuff
    for(/*...*/)
        v.push_back(/*...*/);

    return v;
}();

A return statement must already appears in a scope, so there's not a huge benefit to combining it with the above pattern. I could, however imagine it used to clarify an early-out condition which requires such an initialization:

if(/* some corner case */)
    return [&] {
        std::vector<int> v;
    
        // do some stuff
        for(/*...*/)
            v.push_back(/*...*/);
    
        return v;
    }();

... compared to:

if(/* some corner case */) {
    std::vector<int> v;
    
    // do some stuff
    for(/*...*/)
        v.push_back(/*...*/);
    
    return v;
}

... where the return is further away from the condition.

Quentin
  • 62,093
  • 7
  • 131
  • 191
-3
This code demonstrates a feature of c++ that a lamda can be made constexpr. Which is not possible before c++17.
This code will not work before c++17.

#include <iostream>

constexpr int Increment(int value) {
    return [value] { return value + 1; }();
};


int main()
{
    Increment(10);
    static_assert(11 == Increment(10), "Increment does not work correctly");

    return 0;

}
Sanjeev
  • 115
  • 7