On Wednesday, 30 November 2022 at 03:07:44 UTC, thebluepandabear wrote:
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!");
```

writeln((3000000000LU + 3000000000LU) % uint.max);

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);
```

writeln( cast(uint) -(cast(int)1) );

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

It's always a wraparound (think modulo) but your examples with negative number can be explained because there are hidden unsigned to signed implicit convertions.
That the only special things D does.

Reply via email to