Subtraction

Learn to perform subtraction on pointers.

Introduction

Decrementing and subtraction are very similar to incrementing and addition. The same rules apply:

  • Decrementing a pointer: address = address - sizeof(data type)
  • Subtracting value from a pointer: address = address - value * sizeof(data type)

Example code for decrementing

It’s mostly the same code from the previous lesson. We declare two variables a and b. Then, we start with a pointer to a and decrement it (line 14). By decrementing, the pointer points to variable b.

The code appears to work because, in this case, the compiler placed b on the stack and after it, a.

Get hands-on with 1200+ tech skills courses.