0

Which would be the preferred way of accessing a fixed size array as a circular list?

void foo()
{
  volatile int data[10];
  for(unsigned i = 0; i < 999; ++i)
  {
    data[ i % 10 ] = i;
  }
}


void bar()
{
  volatile int data[10];
  unsigned j = 0;
  for(unsigned i = 0; i < 999; ++i)
  {
    data[ j ] = i;
    j = j > 8 ? 0 : j + 1;
  }
}

I have always been under the impression, that the first form is far, as branching is avoided. However, with gcc 6.2 targeted for x86_64 with -O1, foo() seems to invoke a costly mul instruction and the jump count is the same. Which approach should be the default?

The question is valid for both tagged languages.

Vorac
  • 8,726
  • 11
  • 58
  • 101
  • 1
    Since you have tagged this `C++` and not `C` then why would you not just use [`std::rotate`](http://en.cppreference.com/w/cpp/algorithm/rotate) ? – Paul R Apr 04 '17 at 11:59
  • @PaulR two reasons 1) didn't know about it 2) it seems to modify the array in place. This could bring about problems if the array is constant, or if the objects are heavy. – Vorac Apr 04 '17 at 12:05
  • 2
    The preferred way is to have the size a power of 2 of course. – n. m. could be an AI Apr 04 '17 at 12:10
  • @Vorac: your question is specifically about rotating array *indices* though, not arrays of objects, so `std::rotate` would seem like the obvious choice. Furthermore, if this really is performance-critical, then you should probably benchmark the two C methods above, as well as `std::rotate` for C++, with your particular use case, and see if any one in of them has a significant performance advantage. – Paul R Apr 04 '17 at 12:25
  • @PaulR I was hoping for some general guideline how to write it, as this task seems to come up often. `std::rotate` on an array of indices is a valid answer, but seems awkward to me. I am baffled there isn't even a proposal for `std::circular_list` container adapter, or at least some special `ForwardIterator`. – Vorac Apr 04 '17 at 12:34
  • 1
    Possible duplicate: [Is worth to use mod to replace if statement for circle index](http://stackoverflow.com/q/37676479/253056). – Paul R Apr 04 '17 at 12:36
  • 1
    Possible duplicate of [Is worth to use mod to replace if statement for circle index](http://stackoverflow.com/questions/37676479/is-worth-to-use-mod-to-replace-if-statement-for-circle-index) – Vorac Apr 04 '17 at 13:37

0 Answers0