New! Explore our Programming Academy and AI Tutor - learn to code from scratch, free to start. Explore Now
Programming› C++› Pointers and References

Pointers and References

💻 C++

Understand memory addresses, references and when a pointer is necessary.

Lesson 6 of 9 Tutorial
0 of 9 completed

A pointer holds an address. A reference is another name for an existing object. Both avoid copying, but they behave differently.

By the end of this lesson you can:
  • Declare and dereference pointers.
  • Use references.
  • Avoid dangling pointers.

Pointers

& takes an address and * reads the value at that address. Always check a pointer before dereferencing it.

int score = 88;
int* pointer = &score;

std::cout << pointer << "\n";  // address
std::cout << *pointer << "\n"; // 88

*pointer = 92;
std::cout << score << "\n";    // 92

References

A reference must be initialised and cannot be reseated. It is the safer default for passing values without copying.

int score = 88;
int& alias = score;

alias = 95;
std::cout << score << "\n"; // 95

Lifetime

Never return a pointer or reference to a local variable. It is destroyed when the function ends, leaving a dangling pointer.

Warning Prefer references and standard containers. Use raw pointers only when you need to represent "no object" or interact with C APIs.

Practice

  1. Create a pointer to an int and print both the address and value.
  2. Change a value through a reference.
  3. Explain why returning a reference to a local variable is unsafe.

Hands-on exercise

Write a function swapValues(int& a, int& b) that swaps two numbers using references.
Call it and print the values before and after.

Recap

Pointers store addresses and can be null. References are aliases and cannot be reseated. Watch object lifetimes.

Example

int score = 88;
int* pointer = &score;

std::cout << pointer << "
";  // address
std::cout << *pointer << "
"; // 88

*pointer = 92;
std::cout << score << "
";    // 92

Exercises

Exercise 1. Swap two values Medium
Write a function swapValues(int& a, int& b) that swaps two numbers using references.
Call it and print the values before and after.
C++ exercise-1.txt
Expected Output
3 7
7 3

Lesson Nav

Lesson sections