title: How to efficiently wrap the index of a fixed-size circular buffer
body: <p>I have a fixed size circular buffer (implemented as an array): upon initialization, the buffer gets filled with the specified maximum number of elements which allows the use of a single position index in order to keep track of our current position in the circle.</p>
  
  <p>What is an efficient way to access an element in the circular buffer? Here is my current solution:</p>
  
  <pre><code>int GetElement(int index)
  {
      if (index &gt;= buffer_size || index &lt; 0)
      {
          // some code to handle the case
      }
      else
      {
          // wrap the index
          index = end_index + index &gt;= buffer_size ? (index + end_index) - buffer_size : end_index + index;
      }
  
      return buffer[index];
  }
  </code></pre>
  
  <p>Some definitions:<br>
  <code>end_index</code> is the index of the element immediately after the last element in the circle (it would also be considered the same as the start_index, or the first element of the circle).<br>
  <code>buffer_size</code> is the maximum size of the buffer.</p>