0
0
C++programming~5 mins

Reference vs pointer in C++

Choose your learning style9 modes available
Introduction

References and pointers both let you work with other variables indirectly. They help you change or use data without copying it.

When you want to pass a variable to a function without copying it.
When you want to change the original variable inside a function.
When you want to refer to an object with a simpler name.
When you need to manage memory manually using pointers.
When you want to create dynamic data structures like linked lists.
Syntax
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.

Examples
Reference acts like another name for a. Changing r changes a.
C++
int a = 5;
int &r = a;  // r is a reference to a
r = 10;  // changes a to 10
Pointer p stores address of b. Using *p accesses the value at that address.
C++
int b = 7;
int *p = &b;  // p points to b
*p = 20;  // changes b to 20
Pointers can be changed to point to different variables.
C++
int c = 3;
int d = 4;
int *ptr = &c;
ptr = &d;  // pointer can point to d now
References cannot be reseated to another variable after initialization.
C++
int e = 8;
int &ref = e;
// ref cannot be changed to refer to another variable
Sample Program

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.

C++
#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;
}
OutputSuccess
Important Notes

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.

Summary

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.