What is the difference between a pointer variable and a reference variable?

 

Pointer variables and reference variables are both used in programming to work with memory addresses, but they have some key differences. Here's an explanation with examples in C++:

  1. Pointer Variables:

    • A pointer variable stores the memory address of another variable.
    • Pointers can be reassigned to point to different memory locations.
    • Pointers can be null, which means they don't point to any valid memory location.
    • They are declared using an asterisk (*) before the variable name.
cpp
#include <iostream> int main() { int x = 10; int* ptr = &x; // Declare and initialize a pointer to an int std::cout << "Value of x: " << x << std::endl; std::cout << "Value pointed to by ptr: " << *ptr << std::endl; // Change the value of x indirectly through the pointer *ptr = 20; std::cout << "New value of x: " << x << std::endl; return 0; }
  1. Reference Variables:

    • A reference variable is an alias or another name for an existing variable.
    • Once a reference is established, it cannot be changed to refer to another variable.
    • References must be initialized at the time of declaration, and they cannot be null.
    • They are declared using an ampersand (&) before the variable name.
cpp
#include <iostream> int main() { int x = 10; int& ref = x; // Declare and initialize a reference to an int std::cout << "Value of x: " << x << std::endl; std::cout << "Value referred to by ref: " << ref << std::endl; // Change the value of x directly through the reference ref = 20; std::cout << "New value of x: " << x << std::endl; return 0; }

In the above examples, ptr is a pointer variable that can change where it points, and ref is a reference variable that is bound to x and cannot be changed to refer to another variable. Changes made through the pointer affect the original variable x, while changes made through the reference also affect x.

Comments