Pointers vs References
In C++ we have two ways to work with variable addresses: pointers and references. Both approaches have their advantages and specific uses.
Pointers
int number = 42;
int* pointer = &number; // Pointer to number
*pointer = 10; // Change value through pointer
pointer = nullptr; // Pointer can be empty
Pointers:
- Can be empty (nullptr)
- Can be redirected to another variable
- Require * operator to access the value
- Can perform arithmetic operations (e.g., arrays)
References
int number = 42;
int& reference = number; // Reference to number
reference = 10; // Direct access to value
// reference cannot be empty or change target
References:
- Must be initialized when created
- Cannot be empty
- Cannot change what they refer to
- Are used like normal variables
When to use what?
- Pointers: When we need the ability to change target or work with nullptr
- References: When we know we'll always work with a valid variable
References are safer (cannot be nullptr), but less flexible. Pointers are more powerful, but require more careful handling. In most cases we recommend using references.
Instructions
Run the program and observe the output.
Start programming for free
4/5