When I define and initialize an Array a
:
Is it absolutely absolutely safe, that if (&(a[x]) > &(a[y]))
holds, x > y
is implied?
I am worried about some weird exceptional memory address stuff I have no idea about.
Yes, this is guaranteed. Section 6.5.8p5 of the C standard regarding Relational Operators states:
When two pointers are compared, the result depends on the relative locations in the address space of the objects pointed to. If two pointers to object types both point to the same object, or both point one past the last element of the same array object, they compare equal. If the objects pointed to are members of the same aggregate object, pointers to structure members declared later compare greater than pointers to members declared earlier in the structure, and pointers to array elements with larger subscript values compare greater than pointers to elements of the same array with lower subscript values.
All pointers to members of the same union object compare equal. If the expression P points to an element of an array object and the expression Q points to the last element of the same array object, the pointer expression Q+1 compares greater than P . In all other cases, the behavior is undefined
So even if you have strange memory layouts, the language guarantees that the address of an array element with a higher subscript will compare greater that the address of an array element with a lower subscript. As long as the array subscripts are valid the comparison will hold.
Yes. If x>y
then &a[x] > &a[y]
, if both elements of the array exist, or a[x]
is one element past the end of the array. Otherwise the behavior is undefined.
Note: I see your question asks the inverse of my above answer. The inverse is also true: if the address is greater, then its index is greater, if the address is a whole number of elements apart. Normally the compiler handles this and &a[x]+1
is &a[x+1]
. The compiler translates the +1
in the first expression to adding the number of bytes of the element size.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With