Home > database >  Why can void pointers be subtracted but not added?
Why can void pointers be subtracted but not added?

Time:01-15

Why does

printf("%ld\n", (void *)0 - (void *)0);

compile, but

printf("%ld\n", (void *)0   (void *)0);

does not?

CodePudding user response:

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

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.

CodePudding user response:

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 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.


  1. Note that this is undefined behaviour for void * pointers.
  •  Tags:  
  • Related