why implicitly allowing compare ubyte and byte sucks

Don nospam at nospam.com
Thu Jun 11 17:08:14 PDT 2009


Walter Bright wrote:
> davidl wrote:
>> It seems that comparing two different operands with different size 
>> makes no sense. The compiler should issue an error against that.
> 
> Consider:
> 
>    byte b;
>    if (b == 1)
> 
> here you're comparing two different sizes, a byte and an int. 
> Disallowing such (in its various incarnations) is a heavy burden, as the 
> user will have to insert lots of ugly casts.
> 
> There really isn't any escaping from the underlying representation of 
> 2's complement arithmetic with its overflows, wrap-arounds, sign 
> extensions, etc.

The problem is a lot more specific than that.
The unexpected behaviour comes from the method used to promote two types 
to a common type, when both are smaller than int, but of different 
signedness. Intuitively, you expect the common type of {byte, ubyte} to 
be ubyte, by analogy to {int, uint}->uint, and {long, ulong}->ulong. But 
instead, the common type is int!

The involvement of 'int' in the promotion process is kind of bizarre, 
really. It's a consequence of the fact that in C, short and char are 
second-class citizens, only really intended for saving space. The 
semantics of operations on two different space-saving types are a bit 
problematic.

I think it's true that

byte  == ubyte, byte  == ushort,
short == ubyte, short == ushort

are almost always errors. Could we just make those four illegal?
BTW, it just occured to me that these four (and only these four) are the 
cases where a "signed/unsigned mismatch" warning is actually helpful. A 
signed-unsigned warning involving 'int' is almost always spurious.

For bonus points:



More information about the Digitalmars-d mailing list