First of all, you are subtracting pointers, not dereferenced pointers. If you were hoping to subtract the value of a
from b
via your pointers, you need to be using *p
and *q
.
For the code as written, there is actually no guarantee for what will be output here. In other words, there is no single "correct" answer. You're taking addresses of two automatically allocated variables. The compiler is permitted to put them wherever it wants, so there is no guarantee about how far they lie apart.
Typically though, the compiler will be placing them on the stack, next to one another. So if you subtract their addresses, you'll commonly end up with either 1 or -1.
Note that the types of the pointers are int*
, so pointer arithmetic on them will not be in terms of bytes (perhaps that was what you were expecting?) but units of sizeof(int)
.
Note also that pointer arithmetic beyond a memory "object" isn't strictly well defined according to the standard (see "undefined behaviour"), although most implementations (compilers) don't penalise you for this type of "distance" measurement directly, as it's frequently useful for implementing tree data structures and similar. (At least on modern platforms with linear address spaces.)