Integer overflow and underflow semantics

Alex Rønne Petersen xtzgzorex at gmail.com
Sat May 5 01:42:14 PDT 2012


On 05-05-2012 10:23, Era Scarecrow wrote:
> On Saturday, 5 May 2012 at 07:10:28 UTC, Alex Rønne Petersen wrote:
>
>> Right, but the question was whether the language guarantees what I
>> described. C and C++ don't, and IMO, we should strive to fix that.
>
> I can't see why it wouldn't, unless the compiler adds in checks and
> changes it's behavior or the assembler does it's own quirky magic. The
> bit patterns of how they end up are pretty fixed, it's just how we
> interpret them.

It all depends. GCC (and thus GDC) can target very exotic architectures 
where any assumptions may not, for whatever reason, hold true. This is a 
language design issue more than it's a "how does architecture X or 
compiler Y work" issue.

An interesting problem with undefined behavior for integer overflow and 
underflow in C/C++ is that optimizers are basically free to do anything 
with regards to them, and often do whatever is more convenient for them.

>
> I know before when i needed to know if it overflowed and simulated the
> carry flag, i ended up using a larger type of int. (This was for a
> custom multiple precision unsigned ints)
>
>
>
> Of course now that I think about it, if anything ends up using MMX for
> it's registers, the rules do change a little. MMX don't overflow if I
> remember right, they just cap/truncate to the Max/Min. Since it's
> intended more for multimedia... If the compiler uses those, I can't tell
> you what would happen.

Right, but it's not so much about what *would* happen as much as it is 
about what *should* happen. ;)

-- 
- Alex


More information about the Digitalmars-d mailing list