Is this a bug in Turbo C 2.0?

Tim Olson tim at nucleus.amd.com
Sat Mar 10 06:53:44 AEST 1990


In article <E24hr$1 at cs.psu.edu> flee at shire.cs.psu.edu (Felix Lee) writes:
| Re the claim that
| 	short a, b;
| 	long tot = a + b;
| gets the wrong answer if (a + b > 32767),
| >Microsoft C 5.1 (under OS/2) does the same (wrong) thing.
| 
| It's not the wrong thing.  The shorts are promoted to ints, not longs,
| before the addition is performed.  This can overflow if your int is
| shorter than your long, as with many PC compilers.
| 
| If you want to be portable and get the correct answer, you should cast
| (at least one of) the operands to long before adding:
| 	long tot = (long) a + b;

This is correct, but note that in the original poster's case, there
was a large sequence of sums:

	tot = a + b + c + d + e + f;

where tot is a long and the others are shorts.  In this case, it is
not sufficient to cast just one of the operands to a long, because the
order of evaluation of the sums is undefined.  The standard widening
rules apply only to the two operands of an operation, so if we cast
only "a" to be a long, and the compiler chose to evaluate the sums
from right-to-left, then only the last sum would be done with long
operands.


	-- Tim Olson
	Advanced Micro Devices
	(tim at amd.com)



More information about the Comp.lang.c mailing list