Arithmetic Operators
C provides five basic arithmetic operators:
+ (addition), - (subtraction), * (multiplication), / (division), and % (modulo, the remainder of integer division). These operators work on integer and floating-point types, and understanding exactly how they behave — especially with mixed types and negative numbers — avoids some of the most common bugs in beginner C code.C
#include <stdio.h>
int main(void) {
int a = 10, b = 3;
printf("%d\n", a + b); // 13
printf("%d\n", a - b); // 7
printf("%d\n", a * b); // 30
printf("%d\n", a / b); // 3 (integer division truncates)
printf("%d\n", a % b); // 1 (remainder)
return 0;
}Integer Division Truncates
7 / 2 is 3, not 3.5
When both operands of
/ are integers, C performs integer division: the fractional part is discarded (truncated toward zero). This trips up many beginners who expect division to always yield a precise, fractional answer. To get a fractional result, at least one operand must be a floating-point type.C
int a = 7, b = 2;
printf("%d\n", a / b); // 3 (integer division)
printf("%f\n", (double) a / b); // 3.5 (one operand cast to double)
printf("%f\n", 7.0 / 2); // 3.5 (a literal 7.0 forces double math)Modulo Only Works on Integers
The
% operator is only defined for integer operand types in standard C — writing 10.5 % 3 is a compile error. To compute a remainder for floating-point values, use fmod() from <math.h> instead.C
#include <math.h>
#include <stdio.h>
int main(void) {
int wholeRemainder = 10 % 3; // 1 — fine, both operands are int
/* double bad = 10.5 % 3; */ // ERROR: % does not accept doubles
double floatRemainder = fmod(10.5, 3.0); // 1.5 — use fmod instead
printf("%d %f\n", wholeRemainder, floatRemainder);
return 0;
}Mixing int and float in Arithmetic
When an expression mixes an
int with a double (or float), C implicitly promotes the integer operand to the floating-point type before performing the operation — this is called the "usual arithmetic conversions". The result of the whole expression is then a floating-point value.C
int count = 3; double total = 10.0; double average = total / count; // count is promoted to 3.0, average is 3.333...
Modulo with Negative Numbers
Truncation toward zero since C99
For negative operands, the sign of the result of
% was implementation-defined before C99. Since C99, both / and % truncate toward zero, so the result of % has the same sign as the dividend (the left operand). For example, -7 % 2 is -1, and 7 % -2 is 1.C
printf("%d\n", -7 % 2); // -1 (C99+: truncates toward zero)
printf("%d\n", 7 % -2); // 1
printf("%d\n", -7 % -2); // -1+,-,*,/,%are the five arithmetic operators in CInteger
/truncates toward zero; cast an operand todoublefor a fractional result%only accepts integer operands — usefmod()for floating-point remaindersMixed int/float expressions promote the integer operand to floating-point
Since C99,
%truncates toward zero and matches the sign of the dividend