1.5Type conversion, casts and integer division
The idea
When two different types meet in an expression, C quietly converts them to a common type. Integer division throws away the fraction.
Think of it like this: Pouring water between cups of different sizes: everything is poured into the bigger cup first, then you compare or add.
Why it exists
The conversion rules explain why −1 < 1u is false, why 5/2 is 2, and why a char sum can exceed 127.
How it works
- char and short become int first.
- If one operand is floating point, the other becomes floating point.
- If one is unsigned and the sizes match, the signed one becomes unsigned.
- Integer / integer truncates toward zero; the sign of % follows the dividend.
Worked example: -1 < 1u
The signed −1 is converted to unsigned: it becomes 4294967295. Then 4294967295 < 1 is false (0).
Now play with it
- →In the lab, try -1 < u: the result is 0.
- →Compare 5 / 2 and 5 / 2.0 and read the types.
Type each expression and see its type and value. Remember the conversion rules in the table below.
Memory (one box per element, address below)
Gold = the object the expression names. Blue = the element a pointer result points to. Each box stands for one element; real addresses grow by sizeof(element).
| Situation | Rule | Example |
|---|---|---|
| char or short in an expression | promoted to int first | c + c with c = 100 gives 200 (an int) |
| int meets long | int becomes long | 1 + 2L is a long |
| signed meets unsigned (same size) | signed becomes unsigned | −1 < 1u is false (−1 becomes 4294967295) |
| integer meets floating point | integer becomes floating | 5 / 2.0 = 2.5 |
| both integers | integer division, truncates toward 0 | 5 / 2 = 2, −7 / 2 = −3, −7 % 2 = −1 |
| assign double to int | fraction dropped | int n = 3.99 gives 3 |
| assign int to char | low 8 bits kept | char c = 300 gives 44 |
When in doubt, convert both operands to the larger type first and then do the operation.
Check yourself
What does -7 / 2 evaluate to in C?
Exam notes (the dense version)
In a mixed expression both operands are converted to the "bigger" type (the usual arithmetic conversions); char and short first become int. If one operand is unsigned and the other signed of the same size, the signed one becomes unsigned, so -1 < 1u is false. Integer division truncates toward zero (−7/2 = −3, −7%2 = −1). Assigning a double to an int drops the fraction.
Previous year questions: Types, Operators & Expressions (2)
PYQs are grouped by topic, so this is the full set for Types, Operators & Expressions; try the ones that match this subtopic. Open all 2 on the topic page.