Search code examples
clanguage-lawyervoid-pointerspointer-arithmetic

Why can void pointers be subtracted but not added?


Why does

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

compile, but

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

does not?


Solution

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


    1. Note that this is undefined behaviour for void * pointers, and for pointers that aren't to parts of the same object.