2

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?

2
  • 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. Commented Sep 23, 2020 at 22:57
  • 2
    Let inc = 1 or -1. current=(current+inc +maximum+1)%(maximum+1); Commented Sep 24, 2020 at 0:37

1 Answer 1

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;
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.