ProgrammingModerateMicrosoft/Amazon SDE MCQ · GATE CS

What is printed?

What is printed?
struct K {
    int g() { static int c = 0; return ++c; }
};
int main() {
    K a, b;
    a.g();
    b.g();
    cout << a.g();
}
  1. A. 1
  2. B. 2
  3. C. 3
  4. D. 0

Correct answer: C. 3

A static local variable in a member function exists once for the whole program, not once per object, so all three calls share c: 1, 2, 3.

More OOP with C++ and Java questions

Exams that ask this topic