References and pointers both let you work with other variables indirectly. They help you change or use data without copying it.
Reference vs pointer in C++
int x = 10; int &ref = x; // reference int *ptr = &x; // pointer
A reference is like a nickname for a variable. It must be set when created and cannot be changed to refer to something else.
A pointer holds the address of a variable. It can be changed to point to different variables or be null.
a. Changing r changes a.int a = 5; int &r = a; // r is a reference to a r = 10; // changes a to 10
p stores address of b. Using *p accesses the value at that address.int b = 7; int *p = &b; // p points to b *p = 20; // changes b to 20
int c = 3; int d = 4; int *ptr = &c; ptr = &d; // pointer can point to d now
int e = 8; int &ref = e; // ref cannot be changed to refer to another variable
This program shows how references and pointers both access and change the original variable. It also shows that pointers can point to different variables, but references cannot.
#include <iostream> int main() { int x = 10; int &ref = x; // reference to x int *ptr = &x; // pointer to x std::cout << "x = " << x << "\n"; std::cout << "ref = " << ref << "\n"; std::cout << "*ptr = " << *ptr << "\n"; ref = 20; // changes x std::cout << "After ref = 20; x = " << x << "\n"; *ptr = 30; // changes x std::cout << "After *ptr = 30; x = " << x << "\n"; int y = 40; ptr = &y; // pointer now points to y std::cout << "After ptr = &y; *ptr = " << *ptr << "\n"; // ref = y; // This would change x to 40, not ref to y return 0; }
References must be initialized when declared and cannot be null.
Pointers can be null and can be reassigned to point to different variables.
Use references when you want simpler syntax and guaranteed valid objects.
References are aliases for variables and cannot be changed to refer to something else.
Pointers hold addresses and can be reassigned or set to null.
Both let you work with variables indirectly to save memory and allow changes.