I want to decrease a value by one and if it reaches zero, set it to the maximum value. Is there a way to do this via math without resorting to if (n-1 == 0) { n = max; }
The opposite scenario of increasing a value by one and then setting it to zero when it is greater than max can easily be achieved using n = (n + 1) % (max + 1);
. Furthermore, this is even better since you can increase by whatever amount (not just one) and it will still "wrap" correctly.
Thanks for the answers so far. To be clear, I meant without any boolean logic (if/else) or boolean operators (!, &&, etc) at all. I was just curious as to how to do this. Does the correct answer below really make it more unreadable as long as a comment is provided? It would be necessary to use that for the more general case for subtracting an arbitrary number and expecting the correct wrap around.