简体   繁体   中英

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++?

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;

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);

此代码应该适用于通过区间[0,范围]递减i

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM