c-plus-plus
  1. c-plus-plus-references

C++ Pointers References

Syntax

type& var_name = other_var;

Example

#include <iostream>
using namespace std;

int main() {
   int num = 10;
   int& ref = num;

   cout << "num = " << num << ", ref = " << ref << endl;
   ref++;
   cout << "num = " << num << ", ref = " << ref << endl;

   return 0;
}

Output

num = 10, ref = 10
num = 11, ref = 11

Explanation

In C++, a reference is a name that can be used to refer to an existing variable, just like a pointer. But unlike a pointer, a reference cannot be NULL and cannot be assigned a different address. Instead, it simply provides a new name for an existing variable.

In the example above, the variable ref is a reference to the variable num. When ref is changed, it changes num as well, as they both refer to the same underlying data.

Use

References are often used in C++ to pass arguments to functions, as they allow the function to modify the original variable rather than creating a copy. They are also useful for creating aliases for existing variables, which can lead to more readable code.

Important Points

  • References can only be created for existing variables.
  • References are automatically dereferenced, so there is no need to use the * operator.
  • References cannot be null and cannot be re-assigned to a different address.

Summary

In C++, pointers provide a way to refer to memory locations, while references provide a way to create a new name for an existing variable. References are often used for passing arguments to functions and creating aliases for existing variables. They cannot be null and cannot be re-assigned to a different address.

Published on: