Challenge - 5 Problems
Reference Lifetime Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this code involving reference lifetime?
Consider the following C++ code. What will it print when run?
C++
#include <iostream> int& getReference() { int x = 10; return x; } int main() { int& ref = getReference(); std::cout << ref << std::endl; return 0; }
Attempts:
2 left
💡 Hint
Think about the lifetime of the local variable inside the function.
✗ Incorrect
The function returns a reference to a local variable which is destroyed when the function ends. Using that reference leads to undefined behavior.
❓ Predict Output
intermediate2:00remaining
What is the output of this code with a reference to a static variable?
What will this C++ program print?
C++
#include <iostream> int& getStaticReference() { static int x = 42; return x; } int main() { int& ref = getStaticReference(); ref = 100; std::cout << getStaticReference() << std::endl; return 0; }
Attempts:
2 left
💡 Hint
Static variables live for the entire program duration.
✗ Incorrect
The static variable 'x' persists after the function returns. Changing 'ref' changes 'x', so printing it shows 100.
🔧 Debug
advanced2:00remaining
Which option causes a dangling reference error?
Given these code snippets, which one will cause a dangling reference when compiled and run?
Attempts:
2 left
💡 Hint
Look for references to local variables that do not persist.
✗ Incorrect
Option B returns a reference to a local variable that is destroyed after the function returns, causing a dangling reference.
🧠 Conceptual
advanced2:00remaining
What is the lifetime of a reference to a temporary object?
In C++, what happens to the lifetime of a temporary object when it is bound to a const reference?
Attempts:
2 left
💡 Hint
Think about how const references can extend lifetimes.
✗ Incorrect
Binding a temporary to a const reference extends the temporary's lifetime to the lifetime of the reference.
❓ Predict Output
expert3:00remaining
What is the output and why? (Complex reference lifetime)
Analyze this code and select the correct output.
C++
#include <iostream> int& getRef(bool flag) { if (flag) { static int x = 1; return x; } else { int y = 2; return y; } } int main() { int& r1 = getRef(true); int& r2 = getRef(false); std::cout << r1 << ' ' << r2 << std::endl; return 0; }
Attempts:
2 left
💡 Hint
Consider which references are safe and which are dangling.
✗ Incorrect
r1 refers to a static variable and is safe. r2 refers to a local variable that is destroyed after the function returns, causing undefined behavior.