Question 3.14

Why doesn't the code

int a = 1000, b = 1000;
long int c = a * b;
work?


Under C's integral promotion rules, the multiplication is carried out using int arithmetic, and the result may overflow or be truncated before being promoted and assigned to the long int left-hand side. Use an explicit cast to force long arithmetic:

	long int c = (long int)a * b;
Note that (long int)(a * b) would not have the desired effect.

A similar problem can arise when two integers are divided, with the result assigned to a floating-point variable.

References: K&R1 Sec. 2.7 p. 41
K&R2 Sec. 2.7 p. 44
ANSI Sec. 3.2.1.5
ISO Sec. 6.2.1.5
H&S Sec. 6.3.4 p. 176
CT&P Sec. 3.9 pp. 49-50


Read sequentially: prev next up top


This page by Steve Summit // Copyright 1995 // mail feedback