C++ return by reference: evaluate the two claims We can return a global variable by reference. 2) We cannot return a local variable by reference.

Difficulty: Easy

Correct Answer: Both 1 and 2 are correct.

Explanation:


Introduction / Context:
Returning by reference can avoid copies and enable idioms like chaining assignments. However, a returned reference must remain valid after the function returns. Understanding object lifetime is essential to decide which references are safe to return from a function.


Given Data / Assumptions:

  • Global (or static storage duration) variables outlive function calls.
  • Local automatic variables are destroyed when a function returns.
  • We discuss references to non-temporary objects.


Concept / Approach:

A function may safely return a reference to an object that continues to exist after the function ends, such as a global or static variable, because the reference remains bound to a live object. Conversely, a reference to a local automatic variable becomes dangling as soon as the function returns, leading to undefined behavior. Therefore, returning a global by reference is acceptable, while returning a local by reference is not.


Step-by-Step Solution:

Evaluate claim 1: global variables have static storage duration ⇒ reference remains valid ⇒ correct. Evaluate claim 2: local automatic variables are destroyed at function end ⇒ reference would dangle ⇒ correct. Therefore, both statements are correct. Select “Both 1 and 2 are correct.”


Verification / Alternative check:

Returning a reference to a static local is also permissible because it persists across calls. Compilers with warnings enabled will often flag returning a reference to a local automatic variable as a dangerous error pattern.


Why Other Options Are Wrong:

Only 1 or only 2: ignores the validity of the other correct statement.

Both incorrect: contradicts standard lifetime rules.


Common Pitfalls:

  • Accidentally returning references to temporaries (e.g., the result of an expression), which also dangle.
  • Misunderstanding that returning by value is often safer and optimized via copy elision or move semantics.


Final Answer:

Both 1 and 2 are correct.

More Questions from References

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion