delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1994/11/28/07:19:30

From: ANTHONY APPLEYARD <A DOT APPLEYARD AT fs1 DOT mt DOT umist DOT ac DOT uk>
To: djgpp AT sun DOT soe DOT clarkson DOT edu
Date: Mon, 28 Nov 1994 08:41:12 GMT
Subject: Re: -1441992/4 = 1073381326

  Someone said:
  > This program:
  > int main() { long x = -1441992; unsigned y = 4;
  > printf("%d / %d = %d\n",x,y,x/y); }
  > Spits this out: -1441992 / 4 = 1073381326

  "Mathew J. Hostetter" <iclone!mat AT sloth DOT swcp DOT com> replied on Fri 25 Nov 94
22:11:37 -0700
  > Of course it does; that's how unsigned math works. You're dividing a
32-bit signed number by a 32-bit unsigned number, so C promotion rules dictate
that the signed value be promoted to unsigned before the division takes place.
A negative number promoted to an unsigned type is a large positive number.
Your example in hexadecimal is perhaps less surprising: 0xFFE9FF38 / 0x4 =
0x3FFA7FCE -Mat mat AT ardi DOT com

  But it is still confusing. At least the compiler should warn: "Mixed signed
/ unsigned arithmetic, may give unexpected answers".

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019