Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pointer comparisons “>” with one before the first element of an array object

According to this topic, comparing pointer with one past the last element of an array object is allowed.

And according to @jalf comment, comparing pointer with one before the first element of an array object is forbidden.

example1

int array[10];
int *ptr;
for(ptr=&array[9]; ptr>(array-1); ptr--) {…}

example2

int array[10];
int *ptr;
for(ptr=&array[9]; ptr>=(array); ptr--) {…}
  1. Are both example1 and example2 forbidden?

  2. Is there proof from the C standard that comparing pointer with one before the first element of an array object is forbidden?

like image 754
MOHAMED Avatar asked Apr 26 '13 10:04

MOHAMED


1 Answers

  1. Yes, both are undefined behavior: in the first case, array-1 is undefined; in the second case, ptr becomes undefined when it is decremented after the iteration when it is equal to array.
  2. This is covered by section 6.5.6 of the standard, part 8 (emphasis is mine):

When an expression that has integer type is added to or subtracted from a pointer, the result has the type of the pointer operand. If the pointer operand points to an element of an array object, and the array is large enough, the result points to an element offset from the original element such that the difference of the subscripts of the resulting and original array elements equals the integer expression. In other words, if the expression P points to the i-th element of an array object, the expressions (P)+N (equivalently, N+(P)) and (P)-N (where N has the value n) point to, respectively, the i+n-th and i−n-th elements of the array object, provided they exist. Moreover, if the expression P points to the last element of an array object, the expression (P)+1 points one past the last element of the array object, and if the expression Q points one past the last element of an array object, the expression (Q)-1 points to the last element of the array object. If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined. If the result points one past the last element of the array object, it shall not be used as the operand of a unary * operator that is evaluated.

The standard goes length to cover the element at the position one past the last element of the array object, while the element at the position one prior the first element falls under the "otherwise" clause of the above rule.

like image 150
Sergey Kalinichenko Avatar answered Nov 15 '22 21:11

Sergey Kalinichenko