On 18/07/2025 18:55, Segher Boessenkool wrote:
Hi!
On Fri, Jul 18, 2025 at 06:39:41PM +0200, David Brown wrote:
Are you able to give an example of the C code for which the optimisation
above applies, and values for which the result is affected? (When thinking
about overflows, I always like to use 16-bit int because the numbers are
smaller and easier to work with.)
16 bits? Why so big! :-)
Well, we could test it on the AVR target with "-mint8" in effect, but
some people might worry that 8-bit ints are non-conforming...
Conversion to signed integer types is implementation-defined behaviour in
the C standards, not undefined behaviour. That means the compiler must pick
a specific tactic which is documented (in section 4.5 of the gcc manual) and
applied consistently. It is not undefined behaviour - code that relies on
two's complement conversion of unsigned types to signed types is not
incorrect code, merely non-portable code. (In practice, of course, it is
portable, as all real-world compilers use the same tactic on two's
complement targets.)
Leaving it as UB is a correct implementation. If that is documented it
is IB then, but what is the difference here :-)
No, UB is /not/ a correct implementation of signed integer conversions.
It has to be defined and documented, but the implementation can choose
the details.