What does the % really do anyway? Like when you use it like func()%5;.
What does the % really do anyway? Like when you use it like func()%5;.
It's called the modulus, or modulo, operator. It returns the remainder of one integer divided by another. So 12%5 is 2, because 12/5 is 2 r 2.
[edit] Check out the tutorial! http://www.cprogramming.com/tutorial/modulus.html [/edit]
dwk
Seek and ye shall find. quaere et invenies.
"Simplicity does not precede complexity, but follows it." -- Alan Perlis
"Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
"The only real mistake is the one from which we learn nothing." -- John Powell
Other boards: DaniWeb, TPS
Unofficial Wiki FAQ: cpwiki.sf.net
My website: http://dwks.theprogrammingsite.com/
Projects: codeform, xuni, atlantis, nort, etc.
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% 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]
Last edited by OnionKnight; 06-21-2007 at 06:55 PM.
The x86 processor automatically calculates both the modulus and division when performing division. Good compilers can make calculations involving both very efficient.
If either operand of % 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).