Does c99/c++03
guarantee that &a+1 > &a
is always true?
for example, there's a (c-like) std::copy
, and
int a = 0 ;
int b[9] ;
std__copy(&a , &a+1 , b) ;
Does this always work?
Does c99/c++03
guarantee that &a+1 > &a
is always true?
for example, there's a (c-like) std::copy
, and
int a = 0 ;
int b[9] ;
std__copy(&a , &a+1 , b) ;
Does this always work?
Yes, C99 has special wording to say that when working with addresses, any given object a
will act like an array of 1 item, so that &a+1
is valid (§6.5.6/7):
For the purposes of these operators, a pointer to an object that is not an element of an array behaves the same as a pointer to the first element of an array of length one with the type of the object as its element type.
Though the section number is different (§6.3.6), C90 gives the same requirement.
C++ has the same requirement in §5.7/4 (same section number in both C++03 and C++11).
In C++, you can compare addresses of arbitrary objects (of the same type) using std::less
, even when the built in <
operator would not yield meaningful results (e.g., two objects that are not parts of the same array) (§20.8.5/7):
For templates
greater
,less
,greater_equal
, andless_equal
, the specializations for any pointer type yield a total order, even if the built-in operators <, >, <=, >= do not.
Also note that although you can form these addresses, and can compare them to the address of the object, you cannot dereference these pointers (well, the compiler probably won't stop you if you try, but the result will be undefined behavior).
Yes, that is guaranteed in C++ (don't know about C). The specifics is that a variable of type T is equivalent to an array of a single element of the same type, and you can always obtain a pointer beyond the end of an array.