Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!mnetor!uunet!husc6!cmcl2!brl-adm!adm!jdickson@zook.Jpl.Nasa.GOV From: jdickson@zook.Jpl.Nasa.GOV (Jeff Dickson) Newsgroups: comp.lang.c Subject: MSC C arithmetic Message-ID: <8792@brl-adm.ARPA> Date: Thu, 13-Aug-87 22:10:54 EDT Article-I.D.: brl-adm.8792 Posted: Thu Aug 13 22:10:54 1987 Date-Received: Sat, 15-Aug-87 11:52:57 EDT Sender: news@brl-adm.ARPA Lines: 47 I recently wrote a program for the PC that performed some arithmetic. I compiled the code using MSC 'C' 4.0 . The problem I had, was that simple integer and floating point arithmetic was not being carried out properly unless I explicitly cast the operands to the type of the result. One of the expressions involved multiplying two integers and placing the result in a long integer. The code looked something like this: unsigned int repeat_cnt; unsigned int units; unsigned long n; for (n = repeat_cnt * units; n > 0; n--) If repeat_cnt equaled 10,000 and units equaled 10, n did not get set to 100,000! Rather n got set to 34,464 - which is what the result would be if n were an int not a long (100,000 - 65,536). However, if I explicitly cast the values as longs then n got assigned correctly. for (n = (long)repeat_cnt * (long)units; n > 0; n--) I had a similiar problem with a floating point expression. Not explicitly casting the operands to float caused a completely bogus result. In this case, the expression looked something like this: double total_bits; unsigned int repeat_cnt; unsigned int units; unsigned int blksiz; total_bits = repeat_cnt * units * blksiz * 16.0 If I interpret K & R correctly, explicit casting of the above operands and the operands in the first example are not necessary. What gives? The Sun will run the above code without modification and yield the expected results. Is this a bug? Or a feature? Or within the spec of the language that leaves it up to the compiler writer to generate code that works or breaks? Jeff S. Dickson jdickson@zook.jpl.nasa.gov