title: Delphi: How to avoid EIntOverflow underflow when subtracting?
body: <p>Microsoft already says, in the documentation for GetTickCount, that you could never compare tick counts to check if an interval has passed. e.g.:</p>
  <p><strong>Incorrect (pseudo-code):</strong></p>
  <pre><code>DWORD endTime = GetTickCount + 10000; //10 s from now
  
  ...
  
  if (GetTickCount &gt; endTime)
     break;
  </code></pre>
  <p>The above code is bad because it is suceptable to rollover of the tick counter. For example, assume that the clock is near the end of it's range:</p>
  <pre><code>endTime = 0xfffffe00 + 10000
          = 0x00002510; //9,488 decimal
  </code></pre>
  <p>Then you perform your check:</p>
  <pre><code>if (GetTickCount &gt; endTime)
  </code></pre>
  <p>Which is satisfied immediatly, since <code>GetTickCount</code> <strong>is</strong> larger than <code>endTime</code>:</p>
  <pre><code>if (0xfffffe01 &gt; 0x00002510)
  </code></pre>
  <hr />
  <h2>The solution</h2>
  <p>Instead you should always subtract the two time intervals:</p>
  <pre><code>DWORD startTime = GetTickCount;
  
  ...
  
  if (GetTickCount - startTime) &gt; 10000 //if it's been 10 seconds
     break;
  </code></pre>
  <p>Looking at the same math:</p>
  <pre><code>if (GetTickCount - startTime) &gt; 10000
  
  if (0xfffffe01 - 0xfffffe00) &gt; 10000
  
  if (1 &gt; 10000)
  </code></pre>
  <p>Which is all well and good in C/C++, where the compiler behaves a certain way.</p>
  <h2>But what about Delphi?</h2>
  <p>But when i perform the same math in Delphi, with overflow checking on (<code>{Q+}</code>, <code>{$OVERFLOWCHECKS ON}</code>), the subtraction of the two tick counts generates an EIntOverflow exception when the <em>TickCount</em> rolls over:</p>
  <pre><code>if (0x00000100 - 0xffffff00) &gt; 10000
  
  0x00000100 - 0xffffff00 = 0x00000200
  </code></pre>
  <p>What is the intended solution for this problem?</p>
  <p>Edit: i've tried to temporarily turn off <code>OVERFLOWCHECKS</code>:</p>
  <pre><code>{$OVERFLOWCHECKS OFF}]
     delta = GetTickCount - startTime;
  {$OVERFLOWCHECKS ON}
  </code></pre>
  <p>But the subtraction still throws an <code>EIntOverflow</code> exception.</p>
  <p>Is there a better solution, involving casts and larger intermediate variable types?</p>
  <hr />
  <h2>Update</h2>
  <p>Another SO question i asked explained why <code>{$OVERFLOWCHECKS}</code> doesn't work. It apparently only works at the <strong>function</strong> level, not the <strong>line</strong> level. So while the following <strong>doesn't</strong> work:</p>
  <pre><code>{$OVERFLOWCHECKS OFF}]
     delta = GetTickCount - startTime;
  {$OVERFLOWCHECKS ON}
  </code></pre>
  <p>the following <strong>does</strong> work:</p>
  <pre><code>delta := Subtract(GetTickCount, startTime);
  
  {$OVERFLOWCHECKS OFF}]
     function Subtract(const B, A: DWORD): DWORD;
     begin
        Result := (B - A);
     end;
  {$OVERFLOWCHECKS ON}
  </code></pre>