ProgrammingHardGATE CS · TCS Digital · Advanced

What is printed? (C++17, assume <iostream> and using namespace std)

What is printed? (C++17, assume <iostream> and using namespace std)
struct T {
    T()  { cout << "T"; }
    ~T() { cout << "~"; }
};
void g() {
    static T t;
    cout << "g";
}
int main() {
    g();
    g();
    cout << "m";
}
  1. A. Tggm~
  2. B. Tg~g~m
  3. C. ggTm~
  4. D. TgTgm~~

Correct answer: A. Tggm~

A function-local static is constructed once, the first time control passes its declaration, and destroyed only at program exit after main returns, so the destructor's '~' comes last.

More OOP with C++ and Java questions

Exams that ask this topic