3 ms·
> If you dive into the C specification, you'll discover that the values I tried to cast lead to undefined behaviour [10] which means that my program could have
by steerablesafe 5y ago
> If you dive into the C specification, you'll discover that the values I tried to cast lead to undefined behaviour [10] which means that my program could have done anything. In practice, the behaviour I observed can be explained very simply.
This is not entirely correct. Note that this is integer conversion as opposed to signed integer arithmetic overflow. The latter is indeed undefined behavior, while the former is implementation defined.
https://cigix.me/c17#6.3.1.3.p3 https://cigix.me/c17#6.3.1.3.p3
> Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.
In C++ since C++20 the result is defined. Before that the result was implementation-defined (without the option to raise a signal).
AFAIK all major compilers do the obvious thing in both C and C++. The undefined behavior of signed integer overflow is indeed used by compiler optimizations.