Thread overview | ||||||
---|---|---|---|---|---|---|
|
December 14, 2015 Inferring an integer literal as ubyte | ||||
---|---|---|---|---|
| ||||
Hello. I was trying to do something like this: ubyte code = to!ubyte(spec, 6) + 16; and got an error saying: cannot implicitly convert expression (cast(int)to(spec, 6) + 16) of type int to ubyte Looking at http://dlang.org/spec/lex.html#IntegerLiteral, sure enough 16 is specified to be inferred as an `int`. I thought that integer literals used to be inferred as the smallest integral type that can fit them – am I mistaken? -- Shriramana Sharma, Penguin #395953 |
December 14, 2015 Re: Inferring an integer literal as ubyte | ||||
---|---|---|---|---|
| ||||
Posted in reply to Shriramana Sharma | They are promoted to int in arithmetic operations unless compiler can prove the value doesn't exceed its range. |
December 14, 2015 Re: Inferring an integer literal as ubyte | ||||
---|---|---|---|---|
| ||||
Posted in reply to Shriramana Sharma | On Monday, 14 December 2015 at 13:33:41 UTC, Shriramana Sharma wrote:
> ubyte code = to!ubyte(spec, 6) + 16;
That's not an integer literal... that's a runtime value of ubyte plus an integer literal.
Since the ubyte is the result of a runtime function, the compiler doesn't know what it will be and thinks it could be anything from 0 to 255, inclusive.
240 + 16 = 256 = too big to fit in a ubyte, to it requires a cast.
ubyte code = 16; // this would work
ubyte code = 239 + 16; // this too
but yours won't because to!ubyte(spec, 6) might just be > 240.
|
December 14, 2015 Re: Inferring an integer literal as ubyte | ||||
---|---|---|---|---|
| ||||
Posted in reply to Adam D. Ruppe | Adam D. Ruppe wrote: > but yours won't because to!ubyte(spec, 6) might just be > 240. Thanks for that explanation. That's clear now. -- Shriramana Sharma, Penguin #395953 |
Copyright © 1999-2021 by the D Language Foundation