Sobes.tech
Junior

Tell about the differences between a reference and a pointer in C/C++.

sobes.tech AI

Answer from AI

A reference can be considered as an alias for an existing object; a pointer contains the memory address of the object.

Characteristic Reference Pointer
Initialization Must be initialized at declaration. May be uninitialized.
Reassignment Cannot be reassigned after initialization. Can point to another object.
Null value Cannot be null. Can be nullptr (C++11) or NULL (C/C++).
Array indexing Does not support direct pointer arithmetic. Supports pointer arithmetic.
Operators Used directly (. for members). Uses * for dereferencing, -> for members.
Size Has no own size, refers to the size of the object. Has a size corresponding to the address size in the system (usually 4 or 8 bytes).
Memory allocation Does not require explicit allocation/deallocation. May require new/delete (in C++).
Usage Often used as function parameters for passing by reference. Used for dynamic memory allocation, low-level access.
// Example of using a reference
int x = 10;
int& ref = x; // ref is an alias for x
ref = 20;     // x is now 20

// Example of using a pointer
int y = 30;
int* ptr = &y; // ptr points to the address of y
*ptr = 40;    // y is now 40

// Pointer can be nullptr
int* null_ptr = nullptr;