⚙️ C++ Beginner

What are pointers and references in C++?

Answer

Pointers store the memory address of another variable. References are aliases — alternative names for existing variables. Pointer basics: int x = 42; int* ptr = &x; // ptr holds address of x *ptr = 100; // Dereference: change x through ptr ptr = nullptr; // Pointer can be reassigned int** pptr = &ptr; // Pointer to pointer. Reference basics: int x = 42; int& ref = x; // ref is an alias for x ref = 100; // Changes x directly // int& ref; // ERROR: reference must be initialized // ref = y; // This reassigns x, not the reference. Key differences: (1) References MUST be initialized at declaration; pointers can be uninitialized (or null); (2) References cannot be null; pointers can be nullptr; (3) References cannot be reseated (made to refer to a different variable); pointers can be reassigned; (4) No arithmetic on references; pointer arithmetic is valid (ptr + 1 moves to next element); (5) Syntax: reference uses ref.member; pointer uses ptr->member or (*ptr).member. const with pointers: const int* ptr; // Pointer to const int (can't change value) int* const ptr; // Const pointer (can't change address) const int* const ptr; // Both const. When to use each: use references when the alias must not be null and won't be reseated (function parameters, return values); use pointers when null is a valid state, when reassignment is needed, or for dynamic allocation.