View Single Post
  #14   Spotlight this post!  
Unread 08-08-2005, 10:24
Alan Anderson's Avatar
Alan Anderson Alan Anderson is offline
Software Architect
FRC #0045 (TechnoKats)
Team Role: Mentor
 
Join Date: Feb 2004
Rookie Year: 2004
Location: Kokomo, Indiana
Posts: 9,113
Alan Anderson has a reputation beyond reputeAlan Anderson has a reputation beyond reputeAlan Anderson has a reputation beyond reputeAlan Anderson has a reputation beyond reputeAlan Anderson has a reputation beyond reputeAlan Anderson has a reputation beyond reputeAlan Anderson has a reputation beyond reputeAlan Anderson has a reputation beyond reputeAlan Anderson has a reputation beyond reputeAlan Anderson has a reputation beyond reputeAlan Anderson has a reputation beyond repute
Re: Strange products upon running code...

Quote:
Originally Posted by neilsonster
I then toyed around with just multiplying some random numbers and 15x30 came out to be -62 somehow.
You've already gotten a solution, so I'll just explain the underlying problem in more detail.

When dealing with constants, C compilers typically treat them as the smallest type that can hold a particular value. In this case, both 15 and 30 can fit in a signed char, which can range from 0 to 255. Arithmetic expressions are also evaluated using the smallest type possible, with any overflows in intermediate or final results simply being ignored.

When you multiply 15 by 30, you get the answer 450. When a C program does it, here's what happens.

15 decimal = 00001111 binary
30 decimal = 00011110 binary
product = 111000010 binary
Only eight bits of the product will fit in the result, giving 11000010 binary, which is -62 decimal in a signed char.

That's one of the things I dislike most about using C in general, and the Microchip compiler in particular. The programmer has to keep track of how large intermediate results might be, and deal with the potential overflows explicitly.