LOGBOOK

HELP

Quiz Entry - updated: 2026.07.07

Why can't arithmetic be distributed over casting in C?

Because the cast can change whether an intermediate result overflows: computing in a narrow type and then widening is not the same as widening first and then computing.

The order matters whenever the arithmetic might overflow the narrower type. The classic case is a widening cast:

int x = 2000000000, y = 2000000000;   // both near INT_MAX

long a = (long)(x + y);     // x + y is done in 32-bit int FIRST and
                            //   overflows, then the wrong result widens
long b = (long)x + (long)y; // each widened to 64-bit FIRST, then added
                            //   -> correct 4000000000
// a != b

x + y is evaluated in int, where 4,000,000,000 doesn't fit, so it overflows before the cast ever happens. Casting each operand to long first gives them room, so the sum is exact.

Rule: cast to the wider type before doing arithmetic that could overflow — don't assume (T)(a op b) == (T)a op (T)b.

From Quiz: REVE1 / Number Representations | Updated: Jul 07, 2026