ProgrammingHardProduct-company placement · C++

Which function returns a reference that is SAFE to use after the call returns?

  1. A. int& f() { int x = 1; return x; }
  2. B. int& g() { static int x = 1; return x; }
  3. C. const int& h() { return 5; }
  4. D. int& k(int x) { return x; }

Correct answer: B. int& g() { static int x = 1; return x; }

A static local lives until the program ends. The others return references to a local variable, a temporary or a by-value parameter, all destroyed when the function returns, leaving a dangling reference.

More OOP with C++ and Java questions

Exams that ask this topic