# C++ Pointer Arithmetic

C++ Pointer Arithmetic: This can be used to perform arithmetic operations on pointers. And there are totally four arithmetic operators present in C++ are ++, – -, + and -. The increment operator (++) will increment the value of the pointer according to the pointer’s type. While the address will be incremented by the size of the pointer’s type. So, the pointer will change its value and will store the address of the next element of the pointer’s type.

## C++ Pointer Arithmetic

### Increment a Pointer (++)

Example:

```#include<iostream>
using namespace std;
const int MAX = 3;
int main () {
int  var[MAX] = {10, 100, 200};
int  *ptr;
//let us have array address in a pointer.
ptr = var;
for(int i = 0; i < MAX; i++) {
cout<<"Address of var[" << i << "] = ";
cout<<ptr << endl;
cout<<"Value of var[" << i << "] = ";
cout<<*ptr << endl;
//point to the next location
ptr++;
}
return 0;
}```

Output:

Value of var = 10
Value of var = 100
Value of var = 200

### Decrement a Pointer (- -)

Example:

```#include<iostream>
using namespace std;
const int MAX = 3;
int main () {
int  var[MAX] = {10, 100, 200};
int  *ptr;
//let us have the address of the last element in the pointer.
ptr = &var[MAX-1];
for (int i = MAX; i > 0; i--) {
cout << "Address of var[" << i << "] = ";
cout << ptr << endl;
cout << "Value of var[" << i << "] = ";
cout << *ptr << endl;
//point to the previous location
ptr--;
}
return 0;
}```

Output:

Value of var = 200
Value of var = 100
Value of var = 10

### Pointer Comparisons

The pointers may be compared by using the relational operators such as = =, <, and >.

Example:

```#include<iostream>
using namespace std;
const int MAX = 3;
int main () {
int  var[MAX] = {10, 100, 200};
int  *ptr;
//let us have the address of the first element in a pointer.
ptr = var;
int i = 0;
while ( ptr <= &var[MAX - 1] ) {
cout<< "Address of var[" << i << "] = ";
cout<< ptr << endl;
cout<< "Value of var[" << i << "] = ";
cout<< *ptr << endl;
//point to the previous location
ptr++;
i++;
}
return 0;
}```

Output: