On Tuesday, 22 January 2013 at 17:10:35 UTC, Thiez wrote:
On Tuesday, 22 January 2013 at 16:31:20 UTC, Era Scarecrow wrote:
I really wouldn't want to have to use BigInt for everything that can't overflow and then check to make sure I can fit it in my smaller variables afterwards along with the extra move. I wouldn't want to use BigInts everywhere, and long's aren't needed everywhere either.

Since D aims to emulate C in this aspect, overflow with uints is probably defined as a wrap-around (like C). In this case it seems to me the check for overflow would simply be '(a+b)<a', no need to cast to longs and BigInts and all that. Of course this may not apply to signed ints...

That merely shortens the size of the check, not where you need to place the checks or how often. Truthfully, in almost all cases the wrap-around or overflow/underflow is an error, usually unchecked. If 1 million were the max, then 1,000,000 + 1 should equal 1,000,001 and not <=0, and if 0 is the minimum, 0 - 1 should not equal >=0.

The only real time I can find overflow wanted is while making something that watches for it explicitly to make use of it. Say we emulate or write the 'ucent' types. That could be done as:

  //addition example obviously
  void add(const uint[4] lhs, const uint[4] rhs) {
    uint[4] val;
    bool carry = false;
    foreach(i, ref v; val) {
      uint tmp = lhs[i];

      v = lhs[i] + rhs[i] + (carry ? 1 : 0);
      carry = v < tmp;
    }

    assert(!carry); //could fail. How to handle this? Ignore?
 }

Now let's say there's a for loop which someone decides they would be clever and use a ubyte (unsigned char) as an index or counter.

 for(ubyte i = 0; i < 1000; i++) {
   writeln(i);
 }

The overflow is an error because the wrong type was selected but doesn't change the obvious logic behind it. You can hide the type behind an alias or similar but that doesn't change the fact it's a bug, and can be easier to detect if we are aware the overflow is happening at all rather than it getting stuck and having to manually kill the process or step through it in a debugger. If it wasn't outputting in some way you could identify it's much harder to find.

Encryption may make use of the overflow/wrap around, but far more likely they use xor or binary operations which don't have those problems.

Reply via email to