-2

What does return [value] is supposed to do.

constexpr int Increment(int value) 
{
    return [value] { return value + 1; }();
};
Konrad Rudolph
  • 482,603
  • 120
  • 884
  • 1,141
Sanjeev
  • 85
  • 7
  • Why use a lambda expression here? – john Sep 06 '20 at 18:42
  • OK got it this is unnamed constexpr lambda inside function ....to evaluate it at compile time. I was confused with syntax. Increment(10); – Sanjeev Sep 06 '20 at 18:52
  • Reopened. This is not just a question about what a lambda expression does. It's about the use of a lambda expression that's written and immediately evaluated, and whether that's appropriate. – Pete Becker Sep 06 '20 at 18:54
  • 1
    @PeteBecker: It's a question that can be answered by informing the user of what a lambda expression in C++ is. It therefore qualifies as a duplicate. And no, the question does not ask about whether this is "appropriate"; it's clearly about the meaning of the grammatical constructs involved. – Nicol Bolas Sep 06 '20 at 18:55
  • 1
    @NicolBolas -- no. The question is about writing a lambda expression and immediately calling it, rather than simply writing the code that's inside the lambda. What does using a lambda expression accomplish that `return value + 1;` doesn't do? – Pete Becker Sep 06 '20 at 18:56
  • lambda expression i know but was confused with the syntax inside function as why () at the end of }. – Sanjeev Sep 06 '20 at 18:57
  • 1
    In what context did you find this code? – mkrieger1 Sep 06 '20 at 19:08
  • Duplicate or Needs More Focus. I favor the duplicate, as it might lead to a question with better focus after the "What is this?" is cleared. ("Why is a lambda used here?", "How does this work with constexpr?", ..) – user2864740 Sep 06 '20 at 19:47
  • @mkrieger1 — you should re-post your follow-up question – Pete Becker Sep 07 '20 at 01:02
  • 1
    @PeteBecker I undeleted and updated my [question](https://stackoverflow.com/questions/63767805/what-is-the-significance-of-returning-the-return-value-of-a-lambda-expression-fr). – mkrieger1 Sep 07 '20 at 10:40

1 Answers1

1

This code demonstrates a feature of c++ that a lamda can be made constexpr. Which is not possible before c++17. there is lamda expression called while return

#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;

}
user2864740
  • 54,112
  • 10
  • 112
  • 187
Sanjeev
  • 85
  • 7
  • Would the code work the same if the body of `Increment` was simply `return value + 1;`? – Pete Becker Sep 06 '20 at 19:52
  • 1
    Honestly, I don't see much value in this kind of questions. We have no way to guess what specific language feature the author intended to demonstrate. – HolyBlackCat Sep 06 '20 at 19:55