How do you iterate backward over circular buffer without a conditional?
Asked Answered
T

2

12

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.

Tippets answered 9/8, 2010 at 5:9 Comment(1)
it is not simply, buffer_size - (iterator + 1) % buffer_size - 1?Amyloid
H
19

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

Hankow answered 9/8, 2010 at 5:16 Comment(0)
C
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.

Cortes answered 9/8, 2010 at 6:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.