samedi 26 mai 2018

What the heck is going on with mod (%) operator in C++?

So, I'm implementing a ring buffer. I got a bug. The culprit is the mod operator. According to C++, -1 % 15 is 0. What??

From ISO14882:2011(e) 5.6-4:

The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined. For integral operands the / operator yields the algebraic quotient with any fractional part discarded; if the quotient a/b is representable in the type of the result, (a/b)*b + a%b is equal to a.

The remainder of the division. Okay. So, according to python and google, -1 % 15 = 14 – that's the 'normal' behavior of mod. However, C++ is funky. -1 % 15 should yield -1, right? After all, -1/15 = 0 in integer division, and therefore the remainder is -1. Yet, I'm clearly getting 0! What the hell is going on?

As an added bonus, -2 % 15 is giving me 14. WHAT!

I'm using g++ -std=c++11

Aucun commentaire:

Enregistrer un commentaire