PATCH: Bad signed int to long long conversion

Vincent Lefevre vincent at
Fri Dec 2 00:54:46 CET 2011

On 2011-12-01 23:27:28 +0100, Torbjorn Granlund wrote:
> I don't mind that somebody patches up all occurences of signed negation
> where the smallest negative value could hypothetically appear.  I just
> never saw any problems with the usage in GMP, and prefer to work on
> problem i think are real.

Wasn't the problem reported on real?

Moreover it is well-known that compilers (in particular GCC) optimize
and assuming wrapping on signed overflows is not reliable. One point
to remember is that compilers use generic rules and don't know what
the developer's intents were, and they don't try to guess. So, even
code with undefined behavior but where the intent is clear may break.
So undefined or implementation-defined behavior, in particular related
to integer overflow and aliasing, is problematic and can be the cause
of incorrect code with a high enough probability.

For GMP, it is not sufficient to say that the problem is real. Such
undefined or implementation-defined behavior may yield wrong results
that may not immediately be detected, and this is quite annoying.

> We actually do avoid right shift of signed numbers in GMP, but that is
> actually a less hypothetical problem.
> Language standards are good things, but we should reap their benefits,
> not become their slaves.

Compilers optimizations are necessarily based on language standards.
They do not break code on purpose. So, you need to take these
standards into account, or compile without optimizations (but then,
don't complain that your code is slow). But even without optimizations,
some code may not behave as the user expects (for instance, i >> 257
on the ARM is equivalent to i >> 1).

Another point is that code with undefined behavior doesn't necessarily
make sense. For instance, with (long long) (- LONG_MIN), it is not
clear whether the user expects a value equal to LONG_MIN or equal
to - LONG_MIN.

Vincent Lefèvre <vincent at> - Web: <>
100% accessible validated (X)HTML - Blog: <>
Work: CR INRIA - computer arithmetic / Arénaire project (LIP, ENS-Lyon)

More information about the gmp-bugs mailing list