Really quick (Probably just stupid) question...

• 06-21-2007
Queatrix
Really quick (Probably just stupid) question...
What does the % really do anyway? Like when you use it like func()%5;.
• 06-21-2007
dwks
It's called the modulus, or modulo, operator. It returns the remainder of one integer divided by another. So 12&#37;5 is 2, because 12/5 is 2 r 2.

 Check out the tutorial! ;) http://www.cprogramming.com/tutorial/modulus.html [/edit]
• 06-21-2007
OnionKnight
Note that modulus and remainder are only the same in the case where both operands are positive values. Other than that a modulus b is basically a as it wraps around (i.e. goes back to 0) as it reaches the limit b, like how a clock goes back to 0 after reaching 12. You can think of a as the distance something travels around a ring with a circumference of b, starting at 0, and a modulus b being the position it stops at.
a modulus b can be calculated by adding/subtracting a with b until it's clamped in the range of 0 to b.

Yes Wikipedia probably explains it better.

[EDIT] Some test values from the Ruby interpreter.
12&#37; 5 => 2
12%-5 => -3
-12% 5 => 3
-12%-5 => -2

12.remainder( 5) => 2
12.remainder(-5) => 2
-12.remainder( 5) => -2
-12.remainder(-5) => -2
[/EDIT]

[EDIT2] Creepy, I just noticed that dwks used 12 and 5 as well :O [/EDIT2]
• 06-21-2007
MacGyver
The x86 processor automatically calculates both the modulus and division when performing division. Good compilers can make calculations involving both very efficient.
• 06-21-2007
robatino
If either operand of &#37; is negative, the sign of the result is machine-dependent. The div() and ldiv() functions can be used to compute the quotient and remainder simultaneously (though the compiler may be able to achieve the same thing without them).