C++ Modulus Operator weirdness

Its surprising that the modulus (%) operator in C++ works upwards, but not downwards. When working on some code, I expected,

-1 % 3 = 2
0 % 3 = 0
1 % 3 = 1
2 % 3 = 2

but ended up with,

-1 % 3 = -1
0 % 3 = 0
1 % 3 = 1
2 % 3 = 2

As a result, you’d need to ensure that either you check that your result is

result = n % 3;
if( result

Or, a better solution might be to change the expression such that the negative case never arises,

{ int n = 0; int inc = -1; cout

Hope this helps someone out there!

--

If you have any questions or thoughts, don't hesitate to reach out. You can find me as @viksit on Twitter.