Signedness aliasing using reinterpret_cast

Aliasing here is perfectly legal. See http://eel.is/c++draft/expr.prop#basic.lval-11.2:

If a program attempts to access the stored value of an object through a glvalue whose type is not similar ([conv.qual]) to one of the following types the behavior is undefined:53

(11.1) the dynamic type of the object,

(11.2) a type that is the signed or unsigned type corresponding to the dynamic type of the object

I think, it is also worth talking about the actual overflow question, which does not necessarily require reinterpret_cast. The very same effect could be achieved with implicit integral conversions

 unsigned x = i;
 ++x;
 i = x; // this would serve you just fine.

This code would be implementation defined pre-C++20, since you would be converting from the value which can't be represented by destination type.

Since C++20 this code will be well-formed.

See https://en.cppreference.com/w/cpp/language/implicit_conversion

On a side note, you might as well start with unsigned type if you want integer overflow semantic.


Your code is perfectly legal, cpp reference is a very good source. You can find the same information in the standard [basic.lval]/11

If a program attempts to access the stored value of an object through a glvalue whose type is not similar ([conv.qual]) to one of the following types the behavior is undefined:

  • the dynamic type of the object,

  • a type that is the signed or unsigned type corresponding to the dynamic type of the object,[...]