int *p = new int;
int a = 10;
cout << a+p;
cout << a-p;
Printing a+p, p+a, p-a gives an address, but a-p gives me an error. Why is this so? Aren't pointer addresses integers? And if so, shouldn't a-p give me a negative value?
In terms of pointer arithmetic, pointers aren't equivalent of "integer representing some address". Even addition isn't that simple:
p+1
doesn't mean "get address value from p variable and increase it by one". Actual address increment amount depends on size of pointed variable, so incrementing int64_t *p
will give different result from incrementing int8_t *p
Why do we have such "strange behavior" for addition and subtraction of pointers? Simple answer: because it's defined that way in C++ standard:
5.7 Additive operators
For addition, either both operands shall have arithmetic or unscoped enumeration type, or one operand shall be a pointer to a completely-defined object type and the other shall have integral or unscoped enumeration type.
For subtraction, one of the following shall hold:
— both operands have arithmetic or unscoped enumeration type; or
— both operands are pointers to cv-qualified or cv-unqualified versions of the same completely-defined object type; or
— the left operand is a pointer to a completely-defined object type and the right operand has integral or unscoped enumeration type.
But there's a reason behind that restriction (which is actually describe on the same page of standard). Pointer arithmetic is intended for the following usage: if p
points to some element in array, p+1
points to the next element, p-1
points to the previous and p1-p2
shows number of elements between p1 and p2. In these terms p1+p2
doesn't make any sense, the same for 1-p
, so they are treated as syntax errors.