& Operators
Pointers
Reference Variables
Pass by Value vs Pass by Reference
int p = 5;
cout << p <<endl; //5
cout << &p <<endl; // Address of p
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”
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:
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;
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.
int x = 10;
int &y = x; // Here y is a reference variable
1. Pass by Value
2. Pass by Reference
- using pointers
- using reference variables