How do references differ from pointers?

In C++, both references and pointers are used to reference variables, but they behave differently in several ways.

Differences Between References and Pointers

  • Syntax: References are created using the & symbol, while pointers use the * symbol.
  • Dereferencing: References are automatically dereferenced, while pointers require explicit dereferencing using the * operator.
  • Nullability: Pointers can be null, whereas references must always refer to a valid object once assigned.
  • Reassignment: References cannot be changed to refer to another object after initialization, while pointers can be reassigned to point to different variables.

Example

// Example of pointer and reference in C++ #include int main() { int a = 10; int b = 20; // Pointer int* ptr = &a; // Pointer to a std::cout << "Pointer: " << *ptr << std::endl; // Outputs 10 // Reference int& ref = b; // Reference to b std::cout << "Reference: " << ref << std::endl; // Outputs 20 // Modifying values *ptr = 15; // Changing value of a via pointer ref = 25; // Changing value of b via reference std::cout << "Modified a: " << a << std::endl; // Outputs 15 std::cout << "Modified b: " << b << std::endl; // Outputs 25 return 0; }

C++ References Pointers Programming C++ Syntax Memory Management