C++ Pointers & Reference Variables

Prateek Narang

Topics

  • & Operators

  • Pointers

  • Reference Variables

  • Pass by Value vs Pass by Reference

'Address Of' Operator ( & )

  • To get the address of a variable, we can use the address-of operator (&)
int p = 5;
cout << p <<endl; //5
cout << &p <<endl; // Address of p

Pointer

int x = 10, y=20;

// Declaring a Pointer
int * xPtr = &x; // a pointer to an integer value 

int *yptr;  // Declare
yptr = &x;  // Assign

In C++, A pointer is a variable that holds the address of another variable. To declare a pointer, we use an asterisk between the data type and the variable name.

An interesting property of pointers is that they can be used to access the variable they point to directly. This is done by preceding the pointer name with the dereference operator (*). The operator itself can be read as "value pointed to by”

Dereference Operator (*)

int x = 10, y=20;

// Declaring a Pointer
int * xPtr = &x; // a pointer to an integer value 


cout << xPtr ; // Address of X
cout << *xPtr ; // Value of X (Derefernce Operator)

Sometimes it is useful to make our pointers point to nothing. This is called a null pointer.

 

We assign a pointer a null value by setting it to address 0:

 

 

Null Pointer

int x = 10, y=20;

// Declaring a Pointer
int * xPtr = &x; // a pointer to an integer value 

// Setting to NULL
xPtr = 0;
int *p = 0;
int *q = NULL;

Reference Variables

A reference variable is an alias, that is, another name for an already existing variable.

Once a reference is initialised with a variable, either the variable name or the reference name may be used to refer to the variable.

 

Reference Variable

int x = 10;

int &y = x; // Here y is a reference variable

Passing variables to functions

1. Pass by Value

2. Pass by Reference

                - using pointers

                - using reference variables

 

Passing data to functions

Made with Slides.com