how to make gcc warn about arithmetic signed overflow

Brian Drummond
Tue Sep 24 07:42:00 GMT 2013

On Mon, 2013-09-23 at 13:38 -0600, Dave Allured - NOAA Affiliate wrote:
> On Sun, Sep 22, 2013 at 10:03 PM, James K. Lowden
> <> wrote:
> > Regarding the OP's query
> >
> >> > int r = ab * bc;
> >
> > although the provided example is simple enough, it's the compiler's
> > job is to generate object code, not to do static analysis.
> >
> > Even if the values are const, in the general case they could be
> > modified by another module or another thread.  The compiler simply
> > doesn't have enough information to warn of every runtime overflow.
> I believe the CPU overflow flag is updated after most integer
> arithmetic instructions.  Does GCC have any facility for checking this
> flag after each integer operation?  

Of course it has. See documentation for the -gnato flag (which,
annoyingly, isn't on by default)

> This would be a runtime check, of
> course, not a compile time check.

Not at all : gcc seems to be quite good at eliminating runtime checks if
it can prove (from integer subtype ranges for example) that they can
never be triggered. For the few remaining checks it does have to plant
runtime code. 

In practice in at least one sizeable example, the overhead from overflow
checks turns out to be about 1%.

In this mode, optimisation such as code reordering poses no trouble:
only assignment to the final variable enforces the constraint.
Intermediate arithmetic, however reordered, is required to have adequate
length (have the pseudo-type Universal Integer.

Unfortunately, as this (AFAIK) only applies to gcc when compiling Ada,
both this and the quite revealing C++ discussion are equally off topic
to the original question.

- Brian

More information about the Gcc-help mailing list