LearnFrenzy
Sign in Take a free test

Functions and Default Arguments · Predict the Output · Question 17

std::function holding lambdas with captures Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 17 Back to Exercise

What is the output of the following C++ program?

main.cpp
#include <functional>
#include <iostream>

std::function<int(int)> make_adder(int n) {
    return [n](int x) { return x + n; };
}

int main() {
    auto add5 = make_adder(5);
    auto add10 = make_adder(10);
    std::function<int(int)> chain = [&](int x) { return add10(add5(x)); };
    std::cout << add5(1) << ' ' << add10(1) << ' ' << chain(1) << '\n';
    return 0;
}
  • A 6 11 16 Correct
  • B 6 11 15
  • C 6 6 16
  • D 1 1 1
Correct Answer: Option A

Each lambda remembers its own copy of n. chain applies add5 then add10: 1 + 5 + 10 = 16.

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