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:
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:
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:
Final Answer:
Both 1 and 2 are correct.
Discussion & Comments