Trusted answers to developer questions

Differences between pointers and references in C++

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

A pointer in C++ is a variable that holds the memory address of another variable.

A reference is an alias for an already existing variable. Once a reference is initialized to a variable, it cannot be changed to refer to another variable.

svg viewer

Pointer

  • It is not necessary to initialize it with a value during declaration.

    int a = 5;
    int *p;
    p = &a;
    
  • It can be assigned a NULL value.

  • It must be dereferenced with a * to access the variable’s value.

  • Arithmetic operations can be performed on it.

  • After declaration, it can be re-assigned to any other variable of the same type.

    int a = 5;
    int *p;
    p = &a;
    int b = 6;
    p = &b;
    

Reference

  • It is necessary to initialize it with a value during declaration.

    int a = 5;
    int &ref = a;
    
    
  • It cannot be NULL.

  • It does not need to be dereferenced and can be used simply by name.

  • Arithmetic operations can not be performed on it.

  • It cannot be re-assigned to any other variable after its initialization.

RELATED TAGS

const pointer
const reference
c++
difference
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?