Arrays

Koroskin Denis 2korden at gmail.com
Sat Mar 29 10:37:43 PDT 2008


On Sat, 29 Mar 2008 18:29:40 +0300, bearophile <bearophileHUGS at lycos.com>  
wrote:

> Koroskin Denis:
>> You said, no protection against integer overflows in D? You are wrong!
>> Permission to add this to Phobos is granted!
>
> I think we may need something faster (inlined) and more automatic  
> (better supported by the compiler).
>
> Bye,
> bearophile

Well, yes. This function should be automatically inlined by a compiler.

And I doubt we need implicit integer overflow checking, because it makes  
noticable slowdown and not always desirable.
However, I'd like to see more language support too. I believe the way it's  
done in C# is just what we need:

"The checked(unchecked) keyword is used to control the overflow-checking  
context for integral-type arithmetic operations and conversions."

"In a checked context, if an expression produces a value that is outside  
the range of the destination type, the result depends on whether the  
expression is constant or non-constant. Constant expressions cause compile  
time errors, while non-constant expressions are evaluated at run time and  
raise exceptions."

"If neither checked nor unchecked is used, a constant expression uses the  
default overflow checking at compile time, which is checked. Otherwise, if  
the expression is non-constant, the run-time overflow checking depends on  
other factors such as compiler options and environment configuration."

checked
{
     int i = int.max;
     ++i;                // throws an exception
}

int t = int.max;
int s = checked(t + 1); // the same goes here

checked
{
     int i = int.max;
     unchecked
     {
         int t = i + 1; // but no exception here
     }
}

int main()
{
     static const int i1 = int.max + 1;              // compile-time error  
here
     static const int i2 = unchecked(int.max + 1);   // but ok here
}

As of now, we have no language support for this and my checked() trick is  
the only way to go.



More information about the Digitalmars-d mailing list