On Friday, 22 December 2017 at 10:14:48 UTC, crimaniak wrote:
My code:
alias MemSize = ushort;
struct MemRegion
{
MemSize start;
MemSize length;
@property MemSize end() const { return start+length; }
}
Error: cannot implicitly convert expression
`cast(int)this.start + cast(int)this.length` of type `int` to
`ushort`
Both operands are the same type, so as I understand casting to
longest type is not needed at all, and longest type here is
ushort in any case. What am I doing wrong?
@property MemSize end() const { return cast(int)(start+length); }
The rule of int promotion of smaller types comes from C as they
said. There are 2 reason to do it that way. int is supposed in C
to be the natural arithmetic type of the CPU it runs on, i.e. the
default size the processor has the least difficulties to handle.
The second reason is that it allows to detect easily without much
hassle if the result of the operation is in range or not. When
doing arithmetic with small integer types, it is easy that the
result overflows. It is not that easy to define portably this
overflow behaviour. On some cpus it would require extra
instructions. D has inherited this behaviour so that copied
arithmetic code coming from C behaves in the same way.
@property MemSize end() const
{
MemSize result = start+length;
assert(result <= MemSize.max);
return cast(int)result;
}
with overflow arithmetic this code is not possible (as is if
MemSize was uint or ulong).