Practice mode C++

What is wrong with the function int& getValue() { int local = 5; return local; }?

Correct answer A. It returns a reference to a local variable that is destroyed when the function returns

Explanation

local has automatic storage duration and is destroyed when getValue returns, so the returned reference dangles. Compilers usually warn, but the code compiles, and using the result is undefined behaviour. Returning by value (int) or returning a reference to something that outlives the call, such as a member or a static object, fixes the problem.

Report a problem

Answer checked How we write and check questions

Tip: press A, B, C or D to answer, and N for the next question.

Advertisement

Have a question about this answer?

Your email address will not be published. Required fields are marked *

Links and website addresses are not allowed in comments.