First, the code you gave doesn't even compile, because all the whole math with sizes smaller than int is executed using int . So the result of a + b is int , and int will not implicitly convert to ubyte , because this is a narrowing of the conversion. If you want to assign it to c , you will need to distinguish it.
ubyte c = cast(ubyte)(a + b);
Now this is clearly an uncontrolled transformation, and it will happily insert 44 into c (since the result of the cast sets the values ββto 100 and 200 ). If you want a test conversion, use std.conv.to :
ubyte c = to!ubyte(a + b);
This will raise a ConvOverflowException (which is a subclass of ConvException ) because the result will not match the requested type.
If you want to make a throw yourself and then check if there was an overflow, then you are essentially the same boat as C / C ++, and there are no carry flags or anything like that. Perhaps such a thing exists if you check the assembly code. I dont know. But language, of course, does not give anything like that. std.conv.to shows this by checking the result and seeing if it is too small (depending on the sign and type of argument).
Jonathan m davis
source share