Is this a bug in Turbo C 2.0?

Stephen B Coy coy at ssc-vax.UUCP
Sat Mar 10 07:19:02 AEST 1990


In article <60 at datcon.UUCP>, sar at datcon.UUCP (Simon A Reap) writes:
> In article <3210 at pur-phy> murphy at newton.physics.purdue.edu.UUCP
> (William J. Murphy) writes:
> >long SUM;
> >short data1, data2, data3, data4, data5;
> >SUM = data1 + data2 + data3 + data4 + data5;
> >Here is the problem, when the sum of data? < 32767 it sums correctly on both
> >GNU C and TC.  Hwen the sum of data? > 32767, TC does the rollover and 
> >becomes negative while GNU C carries the sum as a long and returns the
> : 
> >SUM = (long)data1 + (long)data2 + (long)data3 + (long)data4 + (long)data5;
> >solved the problem.
> Microsoft C 5.1 (under OS/2) does the same (wrong) thing.  BTW, you only need
> to (long) cast one of the data? to get the right result.

The Real(tm) cause of this problem lies in the fact that the MS-DOS
compilers default to a 16 bit int while GCC defaults to a 32 bit
int.  As stated in K&R Classic, p.41, during arithmetic operations
"char and short are converted to int".  MSC and TC do their
expression evaluation in 16 bit integers and then convert the result
to long (32-bit) for the assignment.  GCC does its evaluation in 32
bit integers and then does the assignment.  Both are legal and
consistant interpretations of the standard.  Caveat programmer.

> yerluvinunclesimon      Opinions are mine - my cat (1CC) has her own ideas
> Reach me at sar at datcon.co.uk, or ...!mcvax!ukc!pyrltd!datcon!sar

Stephen Coy
uw-beaver!ssc-vax!coy



More information about the Comp.lang.c mailing list