using the full range of ubyte with iota

ketmar via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Jan 25 13:36:58 PST 2015


On Sun, 25 Jan 2015 20:42:47 +0000, Dominikus Dittes Scherkl wrote:

> But in a function you need the cast anyway:
> ubyte swapNibbles(ubyte x) { return (x>>4) | (x>>4); } // compiler not
> happy
sure, it can't be happy, as `x` is promoted to int in the expression, so 
the expression result is `int`. better range analysis can prove that the 
resuit can be fit in `ubyte`, of course. or you can do `&0xff` -- the 
compiler is intelligent enough to see that this fits to ubyte too.

> 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
> }
why do you index with `ulong`s in the first place? there is ugly `size_t` 
type for this.

anyway, what you talking about is a missing integer range analysis in 
complier. i'm not sure that it worth adding, as it slows down compilation 
and hiding some potentially bad code. i can grep for `cast`s to see where 
author is playing with fire, but i can't grep for range analysis. ;-)

p.s. `a[x&size_t.max]` works fine in your sample. and to be honest, i 
prefer either this, or `cast` -- any form of explicit type transformation.

p.p.s. what is bad is that compiler happily accepts this:

  int foo (int x) {
    int[10] a;
    return a[x];
  }

WTF?! why, in the name of Ruler of Hell, array indexing with int doesn't 
generate any warning?! D design decision to silently allow conversion of 
`int` to `uint`/`ulong` is conceptually flawed. but this is one of the 
things that will never be fixed, so we have to live with it.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 181 bytes
Desc: not available
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20150125/d75a3f36/attachment.sig>


More information about the Digitalmars-d-learn mailing list