ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
struct Counter {
    static int next() { static int n = 0; return ++n; }
};
int main() {
    cout << Counter::next() << Counter::next() << Counter::next();
}
  1. A. 111
  2. B. 123
  3. C. 000
  4. D. Compile-time error: a static member function cannot contain a local static variable

Correct answer: B. 123

The local static variable n is initialised only once and persists across calls, shared by every invocation of next() regardless of which object (or none) calls it. Each call increments and returns it: 1, then 2, then 3, giving 123.

More OOP with C++ and Java questions

Exams that ask this topic