Is this a bug in Turbo C 2.0?

Felix Lee flee at shire.cs.psu.edu
Fri Mar 9 15:11:40 AEST 1990


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;
--
Felix Lee	flee at shire.cs.psu.edu	*!psuvax1!flee



More information about the Comp.lang.c mailing list