13

Iterating forward through a circular buffer without using a conditional is easy with the remainder operator...

iterator = (iterator + 1) % buffer_size;

I can't for the life of me figure out the reverse operation, iterating backward.

Nick Strupat
  • 4,928
  • 4
  • 44
  • 56

2 Answers2

19

Does iterator = (iterator + buffer_size - 1) % buffer_size work for you? Go one less than all the way around.

Borealid
  • 95,191
  • 9
  • 106
  • 122
0

Borealid's answer works. (note: iterator is set to 0 initially).

Another solution is

iterator = buffer_size - 1 - (buffer_size - iterator) % buffer_size with iterator set to buffer_size initially.

Omair
  • 814
  • 1
  • 10
  • 19