Why there is too many uneccessary casts?

Ali Çehreli acehreli at yahoo.com
Tue Jun 11 17:58:17 PDT 2013


On 06/11/2013 05:48 PM, captaindet wrote:

 > i think part of the problem is that '1' is an int. so the calculation
 > must be promoted to integer.

According to "Integer Promotions" and "Usual Arithmetic Conversions" 
there is no arithmetic operation that is executed in any type narrower 
than int:

   http://dlang.org/type.html

 > if we had byte and ubyte integer literals (suffix b/B and ub/UB?), then
 > if all RHS arguments are (unsigned) bytes the compiler could infer that
 > we are serious with sticking to bytes...

The CPU would have to have special registers to do those operations in. 
(I am under the impression that x86 does not have any arithmetic 
registers for types narrower than int.)

 > ubyte k = 10;    // or optional 10ub
 > ubyte c = k + 1ub;

Things could be that way but I think these rules are inherited from C. 
Here is another surprising effect:

import std.stdio;

void foo(int)
{
     writeln("int");
}

void foo(byte)
{
     writeln("byte");
}

void main()
{
     byte a, b;

     foo(a + b);    // prints "int"
     foo(a);        // prints "byte"
}

Ali



More information about the Digitalmars-d-learn mailing list