CodeBlanks Logo Icon CodeBlanks

What is a reference?

Learn that a reference is an alias for a variable.

What is a reference?

A reference is an alias for an existing variable. Once a reference is declared, every operation through it affects the original variable, because both refer to the same memory location.

Example: int x = 10; int& r = x;. Here r is an alias for x. Writing r = 20; also makes x become 20. Unlike a pointer, a reference cannot be re-bound to another variable after its first binding; it is fixed at initialization.

Reference versus pointer

A reference is like a pointer but safer. A pointer is a separate variable and can be nullptr; a reference is bound to a variable at initialization and cannot be null.

The syntax is also cleaner: you write r, not *p. But a reference is less flexible; it cannot be re-bound. So when you want 'an alias for a variable', choose a reference; when you want 'an independent address', choose a pointer.

Practice Modify through a reference

Declare int x = 10;. Bind a reference with int& r = x;. Write r = 20;. Finally print x with std::cout.

Starter code

main.cpp
#include <iostream>

int main() {
    // Declare x
    // Bind r as a reference to x
    // Assign to r
    // Print x
    return 0;
}

Sample solution

main.cpp
#include <iostream>

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

Expected output

20

Questions and answers

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

1 What is a reference?

  • A memory address
  • A kind of pointer
  • A new variable type
  • An alias for a variable Correct answer

Explanation: A reference is an alias for an existing variable.

2 Reference declaration

Question
int x = 10;
int____ r = x;
Answer
int x = 10;
int& r = x;

Explanation: int& r = x; makes r a reference to x.

3 Match each expression to its meaning

Term Meaning
int& r Reference declaration
int x = 10 Variable declaration
r = 20 Reference assignment
std::cout << x Print

All lessons in Beginner