Somebody originally wrote:

> # I'm a newbie to C and the Palm OS and have only recently started to write 
> # an application with Codewarrior Lite for Mac. So far reading 
> # through this mailing list has given me lots of tips and insights.
> 
> #result = 10 * 3600; // Here I get -29536 instead of 36000 when      

Summarizing three follow-ups:

> I am a 100% amateur, but I'd write
> 
> result = (Long) 10 * 3600;

-----

> OR
> 
> result = (UInt32) 10 * 3600;

-----

> You need to cast the result as type Long.  10 and 3600 are type
> integer, so the result is calculated as type integer.  If you
> cast it,
> 
> result        = (Long) 10 * 3600;
> 
> you should get the correct result.

----- [ end of summaries ]

Sorry, but these are all wrong. Unless you tell the compiler otherwise, 
it interprets integral literals as type int. A literal is a plain old 
number, like 10 or 3600. (The period on that last sentence is 
grammatical, and is NOT a decimal point.) An integral literal is one 
that does not have a decimal point.

In the world of Palm OS, an int is 16 bits, and so has a range of
-32768 through +32767 inclusive.

So, when the compiler sees
    (Long) 10 * 3600
it multiplies an int 10 by an int 3600, then casts the result to a 
long. Unfortunately, the 10 * 3600 = 36000, which is too large for an 
int. The result is a (silent) math overflow. All you're doing is 
casting the wrong value to a long!

If you want to override the compiler's default interpretation of 
literals, you have to tell it. Append an 'L' to a literal to make the 
compiler interpret it as long:
    long result;
    result = 10L * 3600L;

Actually, you need only append the L to one of the literals, because 
the compiler will promote the other literal to the larger size before 
doing the multiplication.

All this, plus much much more about the C language, is in the book "C: 
A Reference Manual" by Harbison and Steele. I have found it to be an 
indispensable resource, and I highly recommend it to EVERY person doing 
C programming.

--
Roger Chaplin
<[EMAIL PROTECTED]>

-- 
For information on using the Palm Developer Forums, or to unsubscribe, please see 
http://www.palm.com/devzone/mailinglists.html

Reply via email to