A "D'oh" moment for me is when I do an obvious coding error but I am not able to see it even in the debugger.
Consider the following section of code:
Would you expect to see the message "String list is empty"? I would. We have only created the string list and just after creating, it should be empty (i.e. the Count property should not be greater than zero).
sl : TStringList;
sl := TStringList.Create;
if (NOT sl.Count > 0) then ShowMessage('String list is empty');
However the message does not get displayed :(
Of course, in my real-world code the entire boolean expression was much more complicated containing several AND'd and OR'd parts.
Now, why the "(NOT sl.Count > 0)" evaluates to false (when the Count IS 0)?
Welcome to the traps of negative boolean expression + bitwise operations on integers!
Yes, I could have written the expression as "(sl.Count = 0)", but alas, it was written as it was with "(NOT sl.Count > 0)".
To fix my error, the correct expression should have been (note the extra parentheses) :
if (NOT (sl.Count > 0)) then ShowMessage('String list is empty');
Now, about the "d'oh" :
The original "(NOT sl.Count > 0)" evaluated to false as
- sl.Count is 0,
- "NOT 0", since "0" is an integer, evaluates as a bitwise expression and returns -1,
- "-1" is NOT greater than 0, thus the final false result of my wrong expression!
Each day I learn something I already knew :) You?