Bird
Raised Fist0
C++programming~20 mins

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

Choose your learning style10 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.

Practice

(1/5)
1. What does reference lifetime in C++ mean?
easy
A. The time it takes to create a reference
B. How long a reference remains valid during program execution
C. The size of the reference in memory
D. The number of references to a variable

Solution

  1. Step 1: Understand what a reference is

    A reference is an alias for another variable, so it must point to valid data.
  2. Step 2: Define lifetime in this context

    Reference lifetime means the duration the reference points to valid memory without becoming invalid.
  3. Final Answer:

    How long a reference remains valid during program execution -> Option B
  4. Quick Check:

    Reference lifetime = validity duration [OK]
Hint: Reference lifetime = how long it stays valid [OK]
Common Mistakes:
  • Confusing lifetime with creation time
  • Thinking lifetime is about memory size
  • Assuming references count how many times used
2. Which of the following is the correct way to declare a reference to an int variable x?
easy
A. int &ref = x;
B. int ref = &x;
C. int &ref();
D. int *ref = x;

Solution

  1. Step 1: Recall reference declaration syntax

    References use & after the type, e.g., int &ref.
  2. Step 2: Check each option

    int &ref = x; correctly declares a reference to x. Others either declare pointers or incorrect syntax.
  3. Final Answer:

    int &ref = x; -> Option A
  4. Quick Check:

    Reference syntax = type &name = variable [OK]
Hint: References use & after type, not * or parentheses [OK]
Common Mistakes:
  • Using * instead of & for references
  • Adding parentheses after reference name
  • Assigning address instead of reference
3. What will be the output of this code?
int &getRef() {
    int x = 10;
    return x;
}

int main() {
    int &r = getRef();
    std::cout << r << std::endl;
    return 0;
}
medium
A. Undefined behavior (likely garbage value)
B. Compilation error
C. 10
D. 0

Solution

  1. Step 1: Analyze function return

    The function returns a reference to a local variable x which is destroyed after the function ends.
  2. Step 2: Understand consequences

    Using that reference in main leads to undefined behavior because x no longer exists.
  3. Final Answer:

    Undefined behavior (likely garbage value) -> Option A
  4. Quick Check:

    Returning local reference = undefined behavior [OK]
Hint: Never return references to local variables [OK]
Common Mistakes:
  • Assuming local variable reference is valid after return
  • Expecting compilation error
  • Thinking it prints 0 always
4. Identify the error in this code snippet:
int& createRef() {
    int temp = 5;
    return temp;
}

int main() {
    int &r = createRef();
    std::cout << r << std::endl;
}
medium
A. Reference variable declared without initialization
B. Missing semicolon after return statement
C. Returning reference to a local variable which is destroyed
D. Using & instead of * for pointer

Solution

  1. Step 1: Check what is returned

    The function returns a reference to temp, a local variable.
  2. Step 2: Understand lifetime issue

    Local variable temp is destroyed when function ends, so reference is invalid.
  3. Final Answer:

    Returning reference to a local variable which is destroyed -> Option C
  4. Quick Check:

    Returning local reference = lifetime error [OK]
Hint: Local variables die after function ends; don't return their references [OK]
Common Mistakes:
  • Thinking compiler allows returning local references safely
  • Confusing references with pointers
  • Ignoring variable lifetime rules
5. How can you safely return a reference from a function in C++?
hard
A. Return a reference to a temporary object
B. Return a reference to a local variable
C. Return a pointer instead of a reference
D. Return a reference to a static or global variable

Solution

  1. Step 1: Understand safe reference return

    References must refer to valid memory after function ends.
  2. Step 2: Identify valid memory sources

    Static or global variables live beyond function scope, so returning their reference is safe.
  3. Step 3: Evaluate other options

    Local variables and temporaries die after function ends; pointers don't guarantee safety here.
  4. Final Answer:

    Return a reference to a static or global variable -> Option D
  5. Quick Check:

    Safe reference return = static/global variable [OK]
Hint: Return references only to static/global variables [OK]
Common Mistakes:
  • Returning references to local variables
  • Confusing pointers with references
  • Returning references to temporary objects
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard