ProgrammingHardTCS NQT · Infosys pattern

What is printed? (function-local static)

What is printed? (function-local static)
int next() {
    static int n = 0;
    return ++n;
}
int main() {
    cout << next() << next() << next();
    cout << next();
}
  1. A. 1234
  2. B. 0123
  3. C. 1111
  4. D. Compilation error: static local needs an initializer every call

Correct answer: A. 1234

A function-local static variable is initialised exactly once, the first time control reaches its declaration, and then persists across all subsequent calls; each call increments the same shared n, giving 1, 2, 3, 4 in call order.

More OOP with C++ and Java questions

Exams that ask this topic