The C++ % modulus (=remainder) operator
The % operator
calculates the remainder after an integer division. For example:
5 % 3 = 2 since 5 divided by 3 is 1
with a remainder of 2.
7 % 2 = 1 since 7 divided by 2 is 3
with a remainder of 1.
The remainder after dividing
a non-negative integer m by a positive integer n will always be between 0 and
n-1 inclusive.
For
example m % 5 will always be between 0 and 4 inclusive.
|
m |
m % 5 |
|
|
0 |
0 |
The values of m % 5 cycle
through 0, 1, 2, 3, 4. |
|
1 |
1 |
|
|
2 |
2 |
|
|
3 |
3 |
|
|
4 |
4 |
|
|
5 |
0 |
|
|
6 |
1 |
|
|
7 |
2 |
|
|
8 |
3 |
|
|
9 |
4 |
|
|
10 |
0 |
|
We can picture the values
of m % 5, placed around a circle. |
|
As we step clockwise around the circle, we
encounter the numbers in the order 0, 1, 2, 3, 4, 0, 1, 2, ...
|
( m + 1 ) % 5 |
= |
m + 1 |
, if 0 <= m
<= 3 |
|
|
= |
0 |
, if m == 4 |
More generally:
|
( m + 1 ) % n |
= |
m + 1 |
, if 0 <= m
<= n-2 |
|
|
= |
0 |
, if m == n-1 |
The following pieces of code are equivalent:
|
m = ( m + 1 ) % n; |
if ( m == n-1 ) m = 0; else m++; |
|
If exactly one of the operands is negative,
the values of m / n and m % n are implementation dependent. In VC++6: -7 / 5 = -1 -7 % 5 = -2 7 / (-5) = -1 7 % (-5) = 2 Other implementations of C++ may calculate: -7 / 5 = -2 -7 % 5 = 3 7 / (-5) = -2 7 % (-5) = -3 |