c++

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 <0 and reset it accordingly,

result = n % 3;
if( result < 0 ) result += 3;

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

{ int n = 0; int inc = -1; cout << (20 + n + inc) % 10; }
9

{ int n = 9; int inc = 1; cout << (20 + n + inc) % 10; }
0

Hope this helps someone out there!

Thinking in C++ by Bruce Eckel is an excellent book

I just finished skimming through Bruce Eckel's Thinking in C++ book - available for free from his website.

Volume 1 covers the basics pretty well and I didn't really do much more than glance at it, but volume 2 is highly recommended for its marvelous treatment of the C++ STL containers and algorithms.

Syndicate content