How to detect overflow
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed Nov 4 00:16:45 PST 2015
On 11/04/2015 12:11 AM, Namal wrote:
>> import core.checkedint;
>>
>> void main() {
>> bool overflowed;
>> auto result = adds(int.max, 1, overflowed); // this overflows
>> adds(1, 2, overflowed); // this does not reset the flag
>>
>> assert(overflowed);
>> }
>>
>> Ali
>
> wow, this I don't understand at all, how do those two operations
> connected to each other? By the bool value?
The 'overflow' parameter is a 'ref' parameter, meaning that these
functions modify the actual 'overflowed' variable above. You can imagine
that they do not set it to 'false' ever:
Imagine that adds() is implemented like the following:
pure nothrow @nogc @safe
int adds(int x, int y, ref bool overflow) {
// ...
if (over_flow_detected) {
overflow = true;
}
}
So, the caller's variable can only go from 'false' to 'true', never the
other way around. (All of this is just a guess. :) )
Ali
More information about the Digitalmars-d-learn
mailing list