CodeBlanks Logo Icon CodeBlanks

Dangling references

Learn the dangling reference concept and safety.

Dangling references

A reference becomes invalid when the variable it is bound to goes out of scope; this is called a dangling reference. For example, if you return a reference to a local variable inside a function, the variable is destroyed when the function exits and the reference is left dangling.

Using a dangling reference is undefined behavior; the program may crash, give wrong results, or appear to work. So when writing a function that returns a reference, you must ensure the target outlives the caller.

Safe usage

To avoid dangling references, follow two simple principles. First: never return a reference to a local variable. Second: the reference's target must outlive the reference itself.

In this lesson's task, you will write the safe reference function increment(int& n). The caller's x lives before and after the function call, so the reference is safe. Reference parameters are safe in this regard.

Practice The increment function

Define a void increment(int& n) function; in the body write n += 1;. In main declare int x = 10;, call increment(x), and print x with std::cout.

Starter code

main.cpp
#include <iostream>

// Define the increment function

int main() {
    // Declare x
    // Add an increment call
    // Print x
    return 0;
}

Sample solution

main.cpp
#include <iostream>

void increment(int& n) {
    n += 1;
}

int main() {
    int x = 10;
    increment(x);
    std::cout << x << "\n";
    return 0;
}

Expected output

11

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is a dangling reference?

  • An uninitialized reference
  • A non-const reference
  • A reference that is not a pointer
  • A reference to a variable that has gone out of scope Correct answer

Explanation: A dangling reference is bound to a variable that has gone out of scope.

2 Match each expression to its meaning

Term Meaning
int& n Reference parameter
Local variable Do not reference
const int& Safe passing
n += 1 Increment

3 increment body

Question
void increment(int& n) { ____ = n + 1; }
Answer
void increment(int& n) { n = n + 1; }

Explanation: n = n + 1; increases n by one.

All lessons in Beginner