Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will "&a+1 > &a" cause an undefined behaviour

Tags:

c++

c

c++03

c99

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?

like image 961
exprosic Avatar asked Apr 30 '13 13:04

exprosic


People also ask

What is the purpose of the will?

Generally speaking, a will is a legal document that coordinates the distribution of your assets after death and can appoint guardians for minor children. A will is important to have, as it allows you to communicate your wishes clearly and precisely.

Will wording examples?

I declare that I am of the age of majority or otherwise legally empowered to make a will, and under no constraint or undue influence. We, the witnesses, sign our names to this document, and declare that the testator willingly signed and executed this document as the testator's last will.

What is the will of law?

A will, or “testament,” is the legal transaction by which an owner of property disposes... A will is valid if it meets the formalities of the law, which usually, but not always, requires that it be witnessed. The advantage of having a will drawn by an attorney arises from his knowledge of what the law requires.


2 Answers

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, and less_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).

like image 91
Jerry Coffin Avatar answered Sep 20 '22 17:09

Jerry Coffin


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.

like image 29
David Rodríguez - dribeas Avatar answered Sep 21 '22 17:09

David Rodríguez - dribeas