Unexpected value returned from method


(Birger Buhl Dinesen) #1

IDE: Visual Studio 2015
Version: 10.0.0.2269
Target (If relevant): Net
Description:

Following method returns an unexpected value:

class method Indberet.CompareDate(DateA: DateTime; DateB: DateTime): Word;
begin
var res := DateA.Date.CompareTo(DateB.Date);
result := if res < 0 then -1 else if res > 0 then 1 else 0;
//or exit… same result
end;

Expected Behavior:
It should return one of the three values -1, 0, 1.

Actual Behavior:
Returns Word max value 65535

Steps:


(Birger Buhl Dinesen) #2

Word is unsigned so of course no -1 value.

Should it raise an exception when you try to set an invalid value (like -1) ?


(Theo) #3

A word is an unsigned 16 bit integer, so I would expect an out of range error, 0 or 1 as result.
But indeed, -1 could be translated to 65535; 0x00 - 0x01 = 0xFF -> 65535


(Birger Buhl Dinesen) #4

Thanks for the description.

This was tricky for me, so for me it would have been nice with an exception, as you also mention.


(Patrick Lanz) #5

Hello Birgen,
In the project properties, there is a “Check for Overflow” setting, that is False by default.
Just set it to True and try again.


(Birger Buhl Dinesen) #6

O.K. Perfect - I will try it out. Thanks.