Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!ames!amdcad!nucleus!tim From: tim@nucleus.amd.com (Tim Olson) Newsgroups: comp.lang.c Subject: Re: Is this a bug in Turbo C 2.0? Message-ID: <29446@amdcad.AMD.COM> Date: 9 Mar 90 20:53:44 GMT References: <3210@pur-phy> <60@datcon.UUCP> Sender: news@amdcad.AMD.COM Reply-To: tim@amd.com (Tim Olson) Organization: Advanced Micro Devices, Inc., Austin, Texas Lines: 32 Summary: Expires: Sender: Followup-To: In article flee@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@amd.com)