Note that there are some explanatory texts on larger screens.

plurals
  1. POShould I use unsigned integers for counting members?
    primarykey
    data
    text
    <p>Should I use unsigned integers for my count class members?</p> <p><strong>Answer</strong></p> <p>For example, assume a class</p> <pre><code>TList &lt;T&gt; = class private FCount : Cardinal; public property Count : Cardinal read FCount; end; </code></pre> <p>That does make sense, doesn't it? The number of items stored in a list can't be negative, so why not use an unsigned integer type for it? I think it's in general a good principle to always use the least general (ergo the most special) type possible.</p> <p>Now, iterating over a list looks like this:</p> <pre><code>for I := 0 to List.Count - 1 do Writeln (List [I]); </code></pre> <p>When the number of items stored in the list is zero, the compiler tries to evaluate</p> <pre><code>List.Count - 1 </code></pre> <p>which results in a nice Integer overflow (underflow to be exact). Combined with the fact that the debugger does not show the appropriate location where the exception occured, this was very hard to find for me.</p> <p>Let me add that if you have overflow checking turned off, the resulting errors will be even harder to track, because then you will often access memory that doesn't belong to you - and that results in undefined behaviour.</p> <p>I will be using plain Integers for all my count members from now on to avoid situations like this.</p> <p>If that's complete nonsense, please point it out to me :)</p> <p>(I just spent an hour tracking an integer overflow in my code, so I decided to share that - most people on here will know that of course, but perhaps I can save someone some time.)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload