A visual guide to C's arithmetic operators (+, -, *, /, %), implicit type conversion, and casts.
7/2=3 (not 3.5)int and double, the int is automatically promoted to double. This is called implicit conversion.int a = 7; double b = 2.0; double result = a / b; // a is auto-promoted to double β 7.0 / 2.0 = 3.5
(target type) before an expression, you can convert it temporarily. This is called a cast.int a = 7, b = 2; // No cast β integer division printf("%d\n", a / b); // 3 (truncated) // With cast β floating-point printf("%f\n", (double)a / b); // 3.500000
(type) expressionint x = 5; double d = (double)x; // 5.0
double d = 3.7; int n = (int)d; // 3 (fractional part truncated)
int sum = 17, n = 3; double avg = (double)sum / n; // 5.666...
(double)(sum / n) first performs the integer division sum / n = 5, then casts 5 to 5.0.| Situation | Code | Why |
|---|---|---|
| Integer division, want a float result | (double)a / b | Make one side double β floating-point division |
| Computing an average | (double)sum / count | Avoid int / int division |
| malloc return value | (int *)malloc(...) | Convert void* to the appropriate pointer type |
| Round a float toward zero | (int)3.7 β 3 | Drop the fractional part |
| Treat a char as a number | (int)'A' β 65 | Get the ASCII code |
int a = 10, b = 3; printf("A: %d\n", a / b); printf("B: %f\n", (double)a / b); printf("C: %f\n", (double)(a / b));
int / int = int β 10/3 = 3 (truncated)(double)a / b β 10.0 / 3 = 3.333333 (cast before divide β float result)(double)(a / b) β (double)(3) = 3.000000 (integer division happens first β cast position matters!)
Check your understanding of this lesson!
int / int truncates the fractional part. So 7 / 2 = 3.
% is the modulo (remainder) operator. 7 / 2 = 3 remainder 1, so the result is 1.
Casting to (double) turns it into floating-point division: 5.0 / 2 = 2.5.
Learning the concepts here + doing exercises in a book is very effective
* These are affiliate links. Your purchases help support this site.