Question about ubyte x overflow, any safe way?

Ali Çehreli acehreli at yahoo.com
Mon Aug 5 01:41:06 UTC 2019


On 08/04/2019 11:12 AM, matheus wrote:
> Hi,
> 
> The snippet below will produce an "infinite loop" because obviously 
> "ubyte u" will overflow after 255:
> 
> import std.stdio;
> void main(){
>      ubyte u = 250;
>      for(;u<256;++u){
>          writeln(u);
>      }
> }
> 
> Question: Is there a way (Flag) to prevent this?
> 
> Matheus.

Two examples with foreach and ranges. The 'ubyte.max + 1' expression is 
int. The compiler casts to ubyte (because we typed ubyte) in the foreach 
and we cast to ubyte in the range:

void main() {
   int count = 0;
   // (Explicit request for) implicit conversion to ubyte
   foreach (ubyte u; ubyte.min .. ubyte.max + 1) {
     ++count;
   }
   assert(count == 256);

   import std.range;
   import std.algorithm;
   import std.conv;
   int count2 = 0;
   // Explicit conversion with to!ubyte
   iota(ubyte.max + 1).map!(to!ubyte).each!(_ => ++count2);
   assert(count2 == 256);
}

Ali



More information about the Digitalmars-d-learn mailing list