Is the following valid C code? (godbolt)
#include <stddef.h>
ptrdiff_t f(size_t n, void *x, void *y)
{
if (!n) return 0;
typedef unsigned char element[n];
element *a = x, *b = y;
return a - b;
}
With -Werror=pointer-arith clang loudly complains about
<source>:8:14: error: subtraction of pointers to type 'element' (aka 'unsigned char [n]') of zero size has undefined behavior [-Werror,-Wpointer-arith]
return a - b;
~ ^ ~
while gcc compiles the code without complaint.
What is the undefined behavior that clang thinks is occuring? The possibility of the subtraction being zero and therefore not a valid pointer to an element of the array or something different? There's no array access being performed, right? So that shouldn't be the case...
If the code does exhibit undefined behavior, is there a simple way to modify the code to be fully conforming, while still using pointers to VM-types?