GeekArticles
Programming
Delphi
Programming
DelphiD'oh! Those Negative Boolean AND Bitwise Expressions :(
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>
Sponsored Links
Related Topics
Subscribe via RSS
Delphi
- A load of ASP.NET related tutorials, articles, tips and tricks!
- How to move PageControl's tabs using drag'n'drop
- Charts in database applications
- Creating Components Dynamically (at Run-Time)
- The role of the "AOwner" parameter in the Create constructor
- Creating a roll up form (with animation)
- Poll: Do you already have some experience with Delphi?
- Creating a database from Delphi code
- TMemoBar - T(Custom)Memo extender
- How to click-and-select a line in TMemo
