LearnFrenzy
Sign in Take a free test

Lambda Expressions · Find the Error · Question 3

Error: a capturing lambda as a function pointer Answer, explanation & discussion

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

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

main.cpp
#include <iostream>

int run(int (*op)(int), int x) { return op(x); }

int main() {
    int bonus = 10;
    std::cout << run([bonus](int x) { return x + bonus; }, 5) << '\n';
    return 0;
}
  • A run must be a template
  • B Only lambdas without captures convert to function pointers; this one captures bonus – take std::function<int(int)> or a template parameter instead Correct
  • C bonus must be a reference
  • D x must be long
Correct Answer: Option B

A function pointer has nowhere to keep the captured value.

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