c - Is it legal to compare a pointer to the beginning of an array with a pointer of the same type pointing before the beginning of the array? -
is program legal c? if so, please support claim (either way) references 1 of language standards.
void f(char *p) { char *q = p - 1; (void)( q < p ); }; int main(void) { char arr[] = "hello"; f( arr ); }
in particular, i'm interested in whether q < p
comparison legal or not.
no, isn't. using pointer doesn't point element of array or 1 past end (i. e. isn't in range [&arr[0], &arr[size]]
) invokes undefined behavior.
c11 standard, 6.5.6.8 ("additive operators"):
if both pointer operand , result [of p + n] point elements of same array object, or 1 past last element of array object, evaluation shall not produce overflow; otherwise, behavior undefined.
(emphasis mine)
Comments
Post a Comment