When to use references vs. pointers in C/C++


Reference variable

Reference variable is an alternate name of already existed variable. It cannot be changed to refer another variable and should be initialized at the time of declaration. It cannot be NULL. The operator ‘&’ is used to declare a reference variable.

The following is the syntax of reference variable.

datatype variable_name; // variable declaration
datatype& refer_var = variable_name; // reference variable

Here,

datatype − The datatype of variable like int, char, float etc.

variable_name − This is the name of variable given by user.

refer_var − The name of reference variable.

The following is an example of reference variable.

Example

 Live Demo

#include <iostream>
using namespace std;
int main() {
   int a = 8;
   int& b = a;
   cout << "The variable a: " << a;
   cout << "\nThe reference variable r: " << b;
   return 0;
}

Output

The variable a: 8
The reference variable r: 8

Pointers

Basically, pointers are variables which stores the address of another variable. When we allocate memory to a variable, the pointer points to the address of the variable.

The following is the syntax of pointers.

datatype *variable_name;

Here,

datatype − The datatype of variable like int, char, float etc.

gvariable_name − This is the name of variable given by user.

The following is an example of pointers.

Example

 Live Demo

#include <stdio.h>
int main () {
   int a = 8;
   int *ptr;
   ptr = &a;
   printf("Value of variable: %d\n", a);
   printf("Address of variable: %d\n", ptr);
   printf("Value pointer variable: %d\n",*ptr);
   return 0;
}

Output

Value of variable: 8
Address of variable: -201313340
Value pointer variable: 8

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 26-Jun-2020

363 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements