Jakub Kuszneruk
Jakub Kuszneruk

Reputation: 1240

decrementation and modulo - how to decrement negative value in one line of code

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

Answers (3)

Ben Voigt
Ben Voigt

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

M.M
M.M

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

Jens Agby
Jens Agby

Reputation: 425

This code should work for decrementing i through the interval [0, range)

--i = (i > 0) * (i % range);

Upvotes: -1

Related Questions