LearnFrenzy
Sign in Take a free test

Lambda Expressions · Find the Error · Question 7

Error: assigning lambdas of different types to one variable Answer, explanation & discussion

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

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

main.cpp
#include <iostream>

int main() {
    bool fast = true;
    auto pick = [](int x) { return x * 2; };
    if (!fast) pick = [](int x) { return x * 3; };
    std::cout << pick(10) << '\n';
    return 0;
}
  • A fast must be const
  • B Each lambda has its own unique type, so a different lambda cannot be assigned to pick; use std::function<int(int)> (or a function pointer for captureless lambdas) Correct
  • C x must be unsigned
  • D Lambdas cannot be inside if
Correct Answer: Option B

Closure types are distinct even when the code looks identical.

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