[comp.sys.mac.programmer] LSC arithmetic problem

nick@lfcs.ed.ac.uk (Nick Rothwell) (04/24/89)

Well, perhaps not a problem, but certainly a "gotcha". The following
declaration:

	long L = (1<<16) + 1;

results in L being (long) 1. Presumably LSC does its intermediate arithmetic
in 16-bit ints, so I'd have to say something like:

	long L = ((long)1 << 16) + 1

to enforce long intermediate values. But, this is a bit of a gotcha, and I
couldn't find any "beware of the leopard" paragraphs in the LSC manual where
it talks about portability.

		Nick.
Nick Rothwell,	Laboratory for Foundations of Computer Science, Edinburgh.
		nick@lfcs.ed.ac.uk    <Atlantic Ocean>!mcvax!ukc!lfcs!nick
~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~
               Fais que ton reve soit plus long que la nuit.

kcr%rushforth@Sun.COM (Kevin Rushforth) (04/25/89)

In article <1837@etive.ed.ac.uk> nick@lfcs.ed.ac.uk (Nick Rothwell) writes:
>Well, perhaps not a problem, but certainly a "gotcha". The following
>declaration:
>
>	long L = (1<<16) + 1;
>
>results in L being (long) 1. Presumably LSC does its intermediate arithmetic
>in 16-bit ints

K&R and the proposed ANSI standard both say that integer arithmetic is
done in "int" precision (whatever that may be for your machine) unless
one or more of the operands is of type long.  On a MAC, the LSC
compiler uses 16-bit ints (don't know about the MPW compiler).  To
ensure that the calculations are done in "long" precision (i.e. 32-bit
arithmetic), you can do what you suggested (cast the constant(s) to
long) or more simply declare the constants as long in the first place:

	long L = (1L << 16) + 1L;

-- 
Kevin C. Rushforth                   | "If winning is not important,
Sun Microsystems                     |  then commander, why keep score?"
                                     |              - Lt. Worf
ARPA: kcr@sun.com                    |
UUCP: <most-backbone-sites>!sun!kcr  |

davely@mcrware.UUCP (Dave Lyons) (05/09/89)

Oops.  I cut the number of the original message.

>Presumably LSC does its intermediate arithmetic
>in 16-bit ints, so I'd have to say something like:
>
>	long L = ((long)1 << 16) + 1
>
>to enforce long intermediate values. But, this is a bit of a gotcha, and I
>couldn't find any "beware of the leopard" paragraphs in the LSC manual where
>it talks about portability.
>
>		Nick.

I think it's generally true that constants are assumed to be the "int"
type unless otherwise specified.  In order to get a "long" constant you
need to say something like 1L (pg. 35 in the old K&R).

Davely			...!sun!mcrware!davely

The usual "only my opinion" stuff applies.