title: Weird results of modulo arithmetic with negative numbers and unsigned denominators
body: <p>I have an array in C that I want to address in manner similar to a circular buffer, so for example: <code>a[-1]</code> would return me the last element of the array.</p>
  
  <p>To do that I tried to use modulo arithmetic (obviously), problem is, I'm getting quite weird results when negative numbers are involved:</p>
  
  <pre><code>-1 % 4 = -1
  -1 % 4U = 3
  </code></pre>
  
  <p>So far, so good.</p>
  
  <pre><code>-1 % 4000 = -1
  (-1+4000U) % 4000U = 3999
  (-1) % 4000U = 3295
  </code></pre>
  
  <p><strong>Question:</strong> The value (3295) does hold for the <code>(a/b)*b + a%b shall equal a, truncated towards zero</code> (for <code>a=-1, b=4000</code>) from C standard (6.5.5#6) so it's not a bug <em>per se</em>, but <em>why</em> is the standard defined this way?! Surely, there must be some logic in this...</p>
  
  <p>How do I have to write <code>a%b</code> to get sensible results for negative <code>a</code> (as <code>(a+b)%b</code> stops working when <code>abs(a)&gt;b</code>)?</p>
  
  <p>Test application:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  int main(int argc, char **argv) {
    int i=0;
  #define MAX_NUM 4000U
    int weird = (i-1)%MAX_NUM;
    printf("%i\n", weird);
    printf("%i\n", (i-1+MAX_NUM))%MAX_NUM);
    printf("a: %i, b: %i, a from equation: %i\n", i-1, MAX_NUM,
      ((i-1)/MAX_NUM)*MAX_NUM + weird);
    return 0;
  }
  </code></pre>