checking for overflow in C

RAMontante bobmon at iuvax.cs.indiana.edu
Thu May 11 00:28:12 AEST 1989


I needed to catch overflows for a calculator program, so I just went
through and wrapped all the operations in inverse operations:

	/*
	 * Is a*b a safe operation?
	 */
	if (a > 1.0  &&  b > 1.0  &&  (MAX_VAL/a) < b)       /* MAX < a*b? */
		report_error( "multiply overflow");
	else if (a < 1.0  &&  b < 1.0  &&  (MIN_VAL/a) > b)  /* MIN > a*b? */
		report_error( "multiply underflow");
	else
		c = a * b;

and similarly for +, -, /.

Of course this roughly doubles such operations, but I couldn't see any
alternative.  Did I miss something?

(This appears to be compiler-dependent "sometimes"; I had to do this
for TurboC v1.5, but v2.0 includes support for SIG_FPE.  I haven't
rewritten the thing yet.)



More information about the Comp.lang.c mailing list