Is there a formula for overflow?

thebluepandabear therealbluepandabear at protonmail.com
Wed Nov 30 03:07:44 UTC 2022


I am reading through Ali's book about D, and he gives the 
following examples for an overflow:

```D
import std.stdio;
void main() {
// 3 billion each
uint number_1 = 3000000000;
uint number_2 = 3000000000;
}
writeln("maximum value of uint: ", uint.max);
writeln("
  number_1: ", number_1);
writeln("
  number_2: ", number_2);
writeln("
  sum: ", number_1 + number_2);
writeln("OVERFLOW! The result is not 6 billion!");
```

The result overflows and is 1705032704.

Also for the second example, it overflows and comes up with the 
value of 4294967286:

```D
void main() {
uint number_1 = 10;
uint number_2 = 20;
writeln("PROBLEM! uint cannot have negative values:");
writeln(number_1 - number_2);
writeln(number_2 - number_1);
}
```

Also a fun one, the following produces 4294967295:

```D
uint number = 1;
writeln("negation: ", -number);
```

But the book doesn't talk about why the D compiler came up with 
these results (and it also goes for division/multiplication) for 
the overflow (or maybe it did further down ?), as in it didn't 
talk about the formula it used for calculating this value.

I am curious as to what formula the D compiler uses for 
calculating 'overflowed' values, if such thing exists? :)

Regards,
thebluepandabear


More information about the Digitalmars-d-learn mailing list