3 ms·
That's probably true, however there's a small catch. Looking at the standard (no difference between C99/C11), chapter 6.5.6 ("additive operators"), point 9 def
by svens_ 10y ago
That's probably true, however there's a small catch.
Looking at the standard (no difference between C99/C11), chapter 6.5.6 ("additive operators"), point 9 defines the behavior of pointer subtraction:
When two pointers are subtracted, both shall point to elements of the same array object,
or one past the last element of the array object; the result is the difference of the
subscripts of the two array elements.
However reading further:
The size of the result is implementation-defined,
and its type (a signed integer type) is ptrdiff_t defined in the <stddef.h> header.
If the result is not representable in an object of that type, the behavior is undefined.
Unlike the (u)intptr_t types, ptrdiff_t is not optional AFAIK. The way I understand it, you could still invoke UB if the implementation uses a very silly type for ptrdiff_t, though I didn't do further research on it.
Still, using pointer difference makes this a lot safer and more portable. Especially on platforms with unusual memory models, where a pointer might not be just a single integer (e.g. segmented memory on x86). Also the operation is Theta(1), so it doesn't impact performance much.