![]() |
VOOZH | about |
Pointers and references are two important C++ features used to access and manipulate data efficiently. While both can refer to existing variables, they differ in syntax, behavior, and use cases.
A pointer is a variable that stores the memory address of another variable. Using pointers, you can access and modify data indirectly through memory addresses.
Value: 10 Address: 0x7fffffffe9c4
Explanation: In above example, ptr stores the memory address of num using the address-of (&) operator. The dereference (*) operator is then used to access and display the value stored at that memory location.
A reference is an alias or alternative name for an existing variable. Any modification made through the reference directly affects the original variable.
Value: 10 Updated Value: 20
Explanation: In above example, ref acts as an alias for num, meaning both names refer to the same variable. Any modification made through ref directly affects the value of num.
| Aspect | Reference | Pointer |
|---|---|---|
| Definition | A reference is an alias for an existing variable. | A pointer is a variable that stores the memory address of another variable. |
| Initialization | Must be initialized when declared and cannot be reassigned. | Can be initialized later and can be reassigned to point to different objects. |
| Nullability | Cannot be null; must always refer to an object. | Can be null, pointing to no object (e.g., nullptr). |
| Syntax | Uses & for declaration and accessing. | Uses * for declaration and dereferencing, & for address-of. |
| Dereferencing | No dereferencing required, ca be used directly like a normal variable. | Must be dereferenced using * to access the value it points to. |
Void Type | A reference can never be void. | A pointer can be declared as void |
Nesting | Reference variable has only one/single level of indirection. | A pointer variable has n-levels/multiple levels of indirection i.e. single-pointer, double-pointer, triple-pointer |
| Pointer Arithmetic | Cannot perform arithmetic operations (e.g., increment or decrement). | Can perform arithmetic operations (e.g., increment or decrement). |
| Use Case | Primarily used for simpler, more readable references to variables. | Used for more complex memory management, dynamic memory allocation, and handling arrays. |
| Example | int& ref = x; | int* ptr = &x; |