using the full range of ubyte with iota

Dominikus Dittes Scherkl via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Jan 25 12:42:47 PST 2015


On Sunday, 25 January 2015 at 18:59:04 UTC, ketmar wrote:
>> auto x2 = (x>>4) | (x<<4); // swap nibbles - but result in an 
>> int!!!!!
>
> this is true for C and C++ too, as all three languages doing 
> "integer
> promotion". the only difference is that D forbids potentially 
> lossy
> assigns.
>
> you best bet is to not use `auto`, but specify required type 
> explicitly.
> or use ints/uints and cast to bytes only when it is necessary.

in normal assignments I never use auto - it's not simpler than 
writing the type explicit but later makes it more complicated to 
see what type it is.

But in a function you need the cast anyway:
ubyte swapNibbles(ubyte x) { return (x>>4) | (x>>4); } // 
compiler not happy

or if you index with a long, even after explicit check:

int foo(ulong x)
{
    int[10] a;
    return (x < 10) ? a[x] : 0; // cannot index with long
}

So there are plenty of places in D where cast is necessary but 
should not be.
I think both of above cases should be safe without cast, and 
enhancing the compilerr that it can handle these cases is more 
important than a iota!"[]".

Until then I prefer paramCast!fn, because this is more flexible 
than the iota extension and my code is full of casts anyway.


More information about the Digitalmars-d-learn mailing list