1

I'm trying to cycle an integer between a minimum and maximum value inside of a range, e.g., 0-2, so that if I increment or decrement the value, it's always inside the range. Anything over maximum should snap to minimum, and anything below minimum should snap to maximum. The following code works fine for incrementing, but not for decrementing:

current=(current+1)%(maximum+1);

Is there a similar trick that would work for decrementing, too?

NS studios
  • 149
  • 14
  • It's not quite clear what you are asking as your current code does the increment and wrap all together. If you are looking to force a value (that may have been changed somewhere above in the code) inside some range, a double ternary operator can do this. – resiliware Sep 23 '20 at 22:57
  • 2
    Let `inc = 1` or `-1`. `current=(current+inc +maximum+1)%(maximum+1);` – chux - Reinstate Monica Sep 24 '20 at 00:37

1 Answers1

3

Decrementing is equivalent to adding maximum when working mod maximum + 1, so as long as a negative current can’t come from anywhere else, maximum remains fixed, and current + maximum can’t overflow the integer type, you can make use of that:

current = (current + maximum) % (maximum + 1);

The operation being the same with just a choice of 1 or maximum is elegant in a way, but keep in mind that the branching version might be both more readable and faster:

/* increment */
current = current == maximum ? 0 : current + 1;

/* decrement */
current = current == 0 ? maximum : current - 1;
Ry-
  • 218,210
  • 55
  • 464
  • 476