In this post, we will learn about pointer arithmetic in C++.

C++ allows a subset of arithmetic operators to work with pointers variables.

Most of the time, pointer arithmetic is used with raw arrays.

## Increment (++) and Decrement (–) on Pointer

(++) increments a pointer to point to the next array element.

So we can use it to loop through array elements.

Similarly, (– –) decrements a pointer to point to the previous array element.

Output

Forward
4
5
6
Backward
-1
6
5

## Addition (+) and Subtraction (-) on Pointer

Addition operator (+) identifies and the type of operand and increments the pointer by n * sizeof(type).

Example: Adding integer(size=4) to the pointer

int *ptr; // ptr = 1000
ptr + 2 // 1000 + 2*4

Similarly, Subtraction operator () decrement the pointer by n * sizeof(type).

Example: Subtracting integer(size=4) from the pointer

int *ptr; // ptr = 1000
ptr - 3 // 1000 - 3*4

Let’s see an example of adding an integer to a pointer.

Output

4
6

Initially, the pointer is pointing to the first element of the array. By adding 1 it gets increment by 4 (1*4) therefore points to 2nd element of the array and so on.

## Subtracting two Pointers

On subtracting two pointers of the same type we get the number of elements between them.

Output: 3

## Comparing two pointers

== operator check whether two pointers points to the same location.

Note: It does not compare the data which they point to.

Output

False
True
False

## Compare the data of Pointers

To compare the data of two pointers we first need to dereference it using * operator then use some comparison operator.

Output: False

If you have any doubts or suggestions comment below.