pk-tle@sics.se (Tommy Levitte) (01/21/89)
Hrmm... I think I found a bug in Turbo C 2.0 . The funny thing is it didn't exist in earlier versions! This tiny program shows it --- #define X 240 #define Y 240 #define Z ((X)*(Y)) void fn(unsigned long i) { printf("%ld %ul\n",i,i) } main() { fn(Z); } ----- Running this gave me a nice surprise: -7936 2147475712 But if I change fn(Z) with fn(57600), it gives me the right numbers: 57600 57600 (57600 = 240*240 !!!!!!!) This gave me problems when I gave exactly that kind of define to malloc() !!! Fix : Put an L at the end of 240 !!!! -- Tommy Levitte pk-tle@draken.nada.kth.se pk-tle@sics.sics.se gizmo@kicki.stacken.kth.se
gwyn@smoke.BRL.MIL (Doug Gwyn ) (01/24/89)
In article <PK-TLE.89Jan21103247@shai.sics.se> pk-tle@sics.se (Tommy Levitte) writes: >(57600 = 240*240 !!!!!!!) Not with 16-bit ints, it doesn't. 240*240 overflows a 16-bit int, with generally unpredictable results. Apparently Turbo C treated the result as -7936, which is what you get on "silent" overflow on a 2's-complement 16-bit machine. That's permissible. As you noted, forcing the computation to be done using longs avoids the overflow.
diamond@csl.sony.JUNET (Norman Diamond) (01/24/89)
In article <PK-TLE.89Jan21103247@shai.sics.se>, pk-tle@sics.se (Tommy Levitte) writes: > #define X 240 > #define Y 240 > #define Z ((X)*(Y)) > > void fn(unsigned long i) > { > printf("%ld %ul\n",i,i) > } > > main() > { > fn(Z); > } > Running this gave me a nice surprise: > -7936 2147475712 Looks like they FIXED a bug in the earlier version. 240 is an int, 240 * 240 is the int -7936, convert it to unsigned long for i and get 2147475712. Tell printf that it's signed long and it changes back to -7936; tell printf that it's unsigned long and you get 2147475712. > But if I change fn(Z) with fn(57600), it gives me the right numbers: > 57600 57600 57600 is a long. Convert it to unsigned long for i and get 57600. The rest is obvious. > Fix : Put an L at the end of 240 !!!! Yes, that is one way to fix your own bug. [Now to fix the bug in inews that requires more of my text than yours] [again] -- Norman Diamond, Sony Computer Science Lab (diamond%csl.sony.jp@relay.cs.net) The above opinions are my own. | Why are programmers criticized for If they're also your opinions, | re-inventing the wheel, when car you're infringing my copyright. | manufacturers are praised for it?