Tech Tutorials Database
GeekArticles Programming Delphi
 

D'oh! Those Negative Boolean AND Bitwise Expressions :(

 
Author: delphi.about.com
Category: Delphi
Comments (0)

in <a Moments</i></a> :: Again, never mind years of programming! <p>A moment for me is when I do an obvious coding error but I am not able to see it even in the debugger. <p>Consider the following section of code: <code><pre> <b>var</b> sl : TStringList; <b>begin</b> sl := TStringList.Create; <b>try</b> <b>if</b> (<b>NOT</b> sl.Count > 0) <b>then</b> list is <b>finally</b> FreeAndNil(sl); <b>end</b>; <b>end</b>; </pre></code> Would you expect to see the message list is 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). <p>However the message does not get displayed :( <p>Of course, in my real-world code the entire boolean expression was much more complicated containing several and parts. <p>Now, why the sl.Count > evaluates to false (when the Count IS 0)? <p>Welcome to the <b>traps of negative boolean expression + bitwise operations on integers</b>! <p>Yes, I could have written the expression as = but alas, it was written as it was with sl.Count > fix my error, the <b>correct expression</b> should have been (note the extra parentheses) : <code><pre><b>if</b> (<b>NOT</b> <b>(</b>sl.Count > 0<b>)</b>) <b>then</b> list is about the : <p>The original sl.Count > evaluated to false as <ol> <li>sl.Count is since is an integer, evaluates as a bitwise expression and returns is NOT greater than 0, thus the final false result of my wrong expression!</li> </ol> <p>Each day I learn something I already knew :) You? <p><b>Related:</b> <ul Is Your Most Common Delphi Programming - Coding Error Moment?</a></li> <li><a your Delphi Coding Errors - How to Prevent Compile / Run Time Errors</a></li> <li><a Errors and Exceptions</a></li> </ul>

Read More...




Sponsored Links




Read Next: CodeRage 6 - Delphi XE 2 and FireMonkey: 17-21 October 2011



 

 

Comments



Post Your Comment:

Your Name:*
e-mail ID:(required for notification)*
Image Verification: 
 
 Subscribe