ProgrammingVery hardMicrosoft/Google SDE MCQ · GATE CS
What is printed (C++17)?
What is printed (C++17)?
int main() {
int x = 0;
auto f = [x]() mutable { return ++x; };
f();
auto g = f;
f();
cout << f() << g() << x;
}- A. 330
- B. 323
- C. 220
- D. 320
Correct answer: D. 320
The lambda owns its own copy of x. After one call it holds 1, and g copies that state. f() then reaches 2 and 3, g() goes from 1 to 2, and the outer x is never touched (0). C++17 sequences the << operands left to right.
More OOP with C++ and Java questions
- What is printed? cpp struct B { }; struct D : B { }; void f(B&) { cout << "B"; } void f(D&) { cout << "D"; } int main() { D d; B& b = d…
- What is printed? cpp struct T { int id; T(int i) : id(i) { cout << "+" << id; } ~T() { cout << "-" << id; } }; T g(1); void f() { static T…
- What is printed? cpp int main() { int a = 1, b = 2; int& r = a; r = b; r = 5; cout << a << b; }
- What is printed? cpp void g(int&) { cout << "L"; } void g(int&&) { cout << "R"; } template <class T> void fwd(T&& x) { g(x)…
- Which line fails to compile? cpp struct B { void hi() { } }; class D1 : B { }; // note: class struct D2 : B { }; // note: struct int…
- Which line fails to compile? cpp struct M { int v; M(int x) : v(x) { } M operator+(const M& o) const { return M(v + o.v); } }; int main()…