c-plus-plus
  1. c-plus-plus-reference-vs-pointer

C++ Pointers Reference vs Pointer

Syntax

// Pointer declaration
int*  ptr;

// Reference declaration
int& ref = value;

Example

// Pointer example
int num = 5;
int* ptr = #
cout << "Value of num: " << *ptr << endl; // Output: Value of num: 5

// Reference example
int num = 5;
int& ref = num;
cout << "Value of num: " << ref << endl; // Output: Value of num: 5

Output

Value of num: 5

Explanation

Pointers and references are used to store the memory address of variables in C++. Pointers are declared using a * before the variable name and references are declared using a & after the variable type.

Pointers can be used to indirectly access the value of a variable by dereferencing the pointer using the * operator. References allow you to directly access the value of a variable by using the reference name.

Use

Pointers and references are commonly used in C++ to pass variables to functions by reference, which allows the function to directly modify the value of the variable. Pointers can also be used to dynamically allocate memory and create data structures like linked lists.

Important Points

  • Pointers and references both allow you to store the memory address of a variable in C++
  • Pointers can be used to indirectly access the value of a variable while references allow direct access
  • Pointers and references are commonly used in C++ to pass variables to functions by reference and create data structures

Summary

Pointers and references are both important constructs in C++ that allow you to store the memory address of a variable and access its value. Knowing how to use both pointers and references is essential for writing efficient and effective C++ code.

Published on: