0
0
C++programming~20 mins

Reference lifetime in C++ - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Reference Lifetime Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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;
}
AUndefined behavior (dangling reference)
B10
C0
DCompilation error
Attempts:
2 left
💡 Hint
Think about the lifetime of the local variable inside the function.
Predict Output
intermediate
2: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;
}
A42
BUndefined behavior
C100
DCompilation error
Attempts:
2 left
💡 Hint
Static variables live for the entire program duration.
🔧 Debug
advanced
2:00remaining
Which option causes a dangling reference error?
Given these code snippets, which one will cause a dangling reference when compiled and run?
Aint& foo(int& a) { return a; }
Bint& foo() { int a = 5; return a; }
Cint& foo() { static int a = 5; return a; }
Dint& foo() { static int a = 5; a += 1; return a; }
Attempts:
2 left
💡 Hint
Look for references to local variables that do not persist.
🧠 Conceptual
advanced
2: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?
AThe temporary object's lifetime is extended to match the lifetime of the const reference.
BThe temporary object is copied and the reference points to the copy.
CThe temporary object lives forever.
DThe temporary object is destroyed immediately after the expression.
Attempts:
2 left
💡 Hint
Think about how const references can extend lifetimes.
Predict Output
expert
3: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;
}
AUndefined behavior Undefined behavior
BCompilation error
C1 2
D1 Undefined behavior
Attempts:
2 left
💡 Hint
Consider which references are safe and which are dangling.