Why can void pointers be subtracted but not added?
It is useful to find the difference between two pointers. This gives an integer (a ptrdiff_t
).[1]
It is useful to add a difference to a pointer, so we can add an integer to a pointer (and vice-versa). The inverse operation of ptrdiff = p2 - p1
is p2 = p1 + ptrdiff
.[1]
However, there's no sensible meaning to adding two pointers together. So that's not allowed.
- Note that this is undefined behaviour for
void *
pointers, and for pointers that aren't to parts of the same object.
For starters this expression
(void *)0 - (void *)0
has undefined behavior because according to the C Standard (6.5.6 Additive operators)
3 For subtraction, one of the following shall hold:
— both operands are pointers to qualified or unqualified versions of compatible complete object types;
The type void
is an incomplete type.
You could write for example
(char *)0 - (char *)0
Some compilers for backward compatibility have their language extensions that allow such an operation for pointers of the type cv void *
.
As for the operator +
then it is just not defined for pointers. For this operator applied to pointers this shall be satisfied
2 For addition, either both operands shall have arithmetic type, or one operand shall be a pointer to a complete object type and the other shall have integer type.
Applying the operator + for pointers does not make a sense.