LearnFrenzy
Sign in Take a free test

Functions and Default Arguments · Functions MCQ · Question 16

Returning a reference to a local variable Answer, explanation & discussion

  • MCQ
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 16 Back to Exercise

What is wrong with int& f() { int x = 5; return x; }?

  • A Nothing
  • B x is destroyed when f returns, so the returned reference dangles – using it is undefined behaviour Correct
  • C References cannot be returned
  • D It returns a copy
Correct Answer: Option B

Return by value (int f()) instead. Returning references is fine only for objects that outlive the call, such as class members or parameters passed by reference.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links