Since pointer arithmetic is defined within the same array I'm in doubt if we can subtract NULL
from another NULL
. I'm concerned about the implementation of:
//first and second can both either be from the same array
//or be both NULL
prtdiff_t sub(void *first, void *second){
//Do I really need this condition?
if(!first && !second)
return (ptrdiff_t) 0;
return second - first;
}
Note: This question about C. If you are looking for C++ question, it is here (the answer is different!). There is also common question for both C and C++.
Subtracting two NULL pointers is not allowed. Section 6.5.6p9 of the C standard states:
Because neither pointer points to an array object, the behavior is undefined.
You also can't subtract two
void *
becausevoid
is an incomplete type, and pointer subtraction depends on knowing the size of the pointed-to object. You could cast each pointer to aintptr_t
and subtract those, however that would give you the byte difference between the pointers, not the index difference.