Reputation: 1240
I've found very gentle way to increment limited variable, just:
++i %= range;
Unfortunately this trick doesn't work for decrement, because -1 % v == -1
.
How can I improve this in C++?
Upvotes: 3
Views: 2693
Reputation: 283684
My understanding is that you want the same interval of [0, range), you just want to move through it in descending order.
It's rather complicated to do for an arbitrary period, but for powers of two (which needn't be constant), you can use
--i; i &= unsigned(range - 1);
which is analogous to the "optimization" of the positive version,
++i; i &= unsigned(range - 1);
One simple way way to do it for an arbitrary range is to use a second variable
++tmp; i = range - 1 - (tmp %= range);
Upvotes: 0
Reputation: 141598
To avoid the negative modulus behaviour you can just make it positive first:
i = (i - 1 + range) % range;
However this is no good if range
is bigger than half of INT_MAX. (or whatever type i
is).
This seems simpler:
i = (i ? i : range) - 1;
Upvotes: 9
Reputation: 425
This code should work for decrementing i
through the interval [0, range)
--i = (i > 0) * (i % range);
Upvotes: -1