Question discussion

What is the output of the following C++ program?#include using namespace std; int main() { int n = 1; auto f = [n]() mutable { return ++n;…

2118Medium DSSSB TGT Computer Science 0 replies 1 views
0

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

#include <iostream>
using namespace std;
int main() {
    int n = 1;
    auto f = [n]() mutable { return ++n; };
    int a = f();
    int b = f();
    cout << a << " " << b << " " << n;
    return 0;
}
  • A2 3 1
  • B2 2 1
  • C2 3 3
  • D2 3 2
Correct answer: A

Explanation

The lambda captures n by value; 'mutable' lets it modify its own copy, which persists between calls (2, then 3), while the outer n stays 1.

Discussion 0

Nobody has replied yet. Start the discussion!