How do the / and % operators work with integers in C?
Integer division (/) truncates toward zero in C99+. The fractional part is discarded.
Modulo (%) returns the remainder after integer division. The sign of the result follows the dividend (numerator) in C99+.
Key rules (C99/C11):
(a/b)*b + a%b == aalways holds.- Truncation toward zero:
7/2 == 3,-7/2 == -3. - Modulo sign follows dividend:
7%2 == 1,-7%2 == -1,7%-2 == 1. - Division by zero is undefined behavior (not just a runtime error -- the compiler can assume it never happens).
Pre-C99: The direction of truncation for negative operands was implementation-defined. C99 standardized truncation toward zero.
1. Integer division truncates toward zero: 7/2 = 3, -7/2 = -3
2. Modulo: (a/b)*b + a%b == a (always holds)
3. Modulo sign follows the dividend: -7%2 = -1
4. Division by zero is undefined behavior
5. Both operands must be integers for %
#include <stdio.h>
int main(void) {
/* Integer division truncates toward zero */
printf(" 7 / 2 = %d\n", 7 / 2); /* 3 */
printf("-7 / 2 = %d\n", -7 / 2); /* -3 (toward zero, not -4) */
printf(" 7 / -2 = %d\n", 7 / -2); /* -3 */
printf("-7 / -2 = %d\n", -7 / -2); /* 3 */
/* Modulo: sign follows dividend */
printf(" 7 %% 2 = %d\n", 7 % 2); /* 1 */
printf("-7 %% 2 = %d\n", -7 % 2); /* -1 */
printf(" 7 %% -2 = %d\n", 7 % -2); /* 1 */
printf("-7 %% -2 = %d\n", -7 % -2); /* -1 */
/* Verify: (a/b)*b + a%b == a */
int a = -7, b = 2;
printf("(%d/%d)*%d + %d%%%d = %d + %d = %d\n",
a, b, b, a, b, (a/b)*b, a%b, (a/b)*b + a%b); /* -7 */
/* % only works with integers */
/* printf("%f", 7.5 % 2.0); // ERROR: invalid operands to % */
/* Use fmod() for floating-point remainder */
return 0;
}
- •Integer division truncates toward zero (C99+)
- •Modulo sign follows the dividend (numerator)
- •(a/b)*b + a%b == a always holds
- •% operator only works on integer types
- •Use fmod() from <math.h> for floating-point remainder
- •Division by zero is undefined behavior, not just a crash -- the compiler can assume it never happens
- •INT_MIN / -1 is undefined behavior on two's complement systems (result overflows)
- •Pre-C99, truncation direction for negative numbers was implementation-defined
- •-7 % 2 is -1 in C99+ but could be 1 in older compilers