Boost logo

Boost :

From: Anthony Williams (anthwil_at_[hidden])
Date: 2002-08-22 03:23:27


Maxim Shemanarev writes:
> > If the committee is seriously considering ways to handle stuff, how about
> > dealing with the two results returned by almost every integer divide
> > instruction... quotient and remainder.
>
> Right. That's another thing. But in this case if you write x=a/b; y=a%b; a
> compiler at least *can try* to optimize this. In case of x*a/b it cannot
> because it's not allowed to!

Everyone is forgetting that integer overflow on signed types results in
undefined behaviour. Since the only case in which you need the intermediate
result to be larger than int is where (x*a) overflows, this expression
yields undefined behaviour in such cases. The upshot of this is that a
compiler is permitted (as an extension) to _define_ such behaviour, and ensure
that x*a/b always yields the mathematically correct result if the final result
fits in an int. Obviously, if the final result doesn't fit in an int, you
still have overflow (e.g. INT_MAX*INT_MAX/1), but this actually allows
implementations to define the result of a*b/c as the mathematically
correct answer where the final answer is in range.

Anthony


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk