title: Signed overflow in C++ and undefined behaviour (UB)
body: <p>I'm wondering about the use of code like the following</p>
  
  <pre><code>int result = 0;
  int factor = 1;
  for (...) {
      result = ...
      factor *= 10;
  }
  return result;
  </code></pre>
  
  <p>If the loop is iterated over <code>n</code> times, then <code>factor</code> is multiplied by <code>10</code> exactly <code>n</code> times. However, <code>factor</code> is only ever used after having been multiplied by <code>10</code> a total of <code>n-1</code> times. If we assume that <code>factor</code> never overflows except on the last iteration of the loop, but may overflow on the last iteration of the loop, then should such code be acceptable? In this case, the value of <code>factor</code> would provably never be used after the overflow has happened.</p>
  
  <p>I'm having a debate on whether code like this should be accepted. It would be possible to put the multiplication inside an if-statement and just not do the multiplication on the last iteration of the loop when it can overflow. The downside is that it clutters the code and adds an unnecessary branch that would need to check for on all the previous loop iterations. I could also iterate over the loop one fewer time and replicate the loop body once after the loop, again, this complicates the code.</p>
  
  <p>The actual code in question is used in a tight inner-loop that consumes a large chunk of the total CPU time in a real-time graphics application.</p>