LearnFrenzy
Sign in Take a free test

Lambda Expressions · Find the Error · Question 6

Error: a lambda calling itself by name Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

The program below does not compile. Which statement correctly describes the problem?

main.cpp
#include <iostream>

int main() {
    auto fact = [](int n) { return n <= 1 ? 1 : n * fact(n - 1); };
    std::cout << fact(5) << '\n';
    return 0;
}
  • A Lambdas cannot use ?:
  • B fact's type is deduced from its initialiser, so the name cannot be used inside its own initialiser; use C++23 this auto self, std::function, or pass the lambda to itself Correct
  • C n must be long
  • D fact must be global
Correct Answer: Option B

[](this auto self, int n) { return n <= 1 ? 1 : n * self(n - 1); } works in C++23.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links