C modulus uses the percent operator (%) to return the remainder after integer division. For example, 17 % 5 is 2, because 17 divided by 5 has a quotient of 3 and a remainder of 2.
The operator accepts integer operands, including signed and unsigned types such as char, int, long, and long long. It does not accept floating-point operands. C converts the operands according to its usual arithmetic conversion rules before calculating the result.
How C modulus calculates a remainder from integer operands
C defines the relationship between division and remainder as:
a = (a / b) * b + (a % b)
For positive operands, the result is straightforward:
- 23 % 7 is 2: 23 = (3 × 7) + 2.
- 40 % 8 is 0: 40 divides evenly by 8.
- 6 % 10 is 6: the divisor is larger than the dividend.
In modern C, integer division truncates toward zero. The remainder is whatever value makes the equation above true, rather than a separately rounded mathematical operation.
Common uses of C modulo: divisibility, parity, and wrapping
Use C modulo whenever you need to test a repeating pattern or determine what remains after groups of equal size.
- Divisibility: number % divisor == 0 is true when the division has no remainder. For example, if (value % 3 == 0) tests whether value is divisible by 3.
- Even or odd values: value % 2 == 0 identifies an even value. A result of 1 identifies a positive odd value.
- Wrapping indexes: index = (index + 1) % size cycles an index from 0 through size – 1. This is useful for circular buffers, rotating menus, and repeating schedules.
For wrapping, make sure size is positive and nonzero. A negative index requires additional handling because C’s remainder is not always nonnegative.
Negative operands and mod in C
In mod in C, the remainder has the sign of the dividend, or left operand, when the result is nonzero:
- -17 % 5 is -2.
- 17 % -5 is 2.
- -17 % -5 is -2.
For the first example, C truncates -17 / 5 toward zero, producing -3. Therefore, -17 = (-3 × 5) + (-2). This differs from mathematical modulo conventions, which commonly require a nonnegative result when the modulus is positive.
If you need a nonnegative result for a positive modulus, normalize it with ((value % modulus) + modulus) % modulus.
Division by zero and surprising cases
The right operand of % cannot be zero. An expression such as count % 0 has undefined behavior, so check the divisor before calculating the remainder.
Also avoid assuming that mixed signed and unsigned operands behave like two signed values. C may convert the signed operand to unsigned before applying %, producing an unexpected result. Keep operand types consistent when possible. Finally, the division and remainder relationship can fail to produce a representable quotient in exceptional cases such as the smallest signed integer divided by -1; do not rely on that operation.
