View Single Post
  #56   Spotlight this post!  
Unread 01-03-2007, 15:22
Dave K.'s Avatar
Dave K. Dave K. is offline
Engineer/Mentor
FRC #0930
Team Role: Mentor
 
Join Date: Jan 2007
Rookie Year: 2005
Location: WI
Posts: 91
Dave K. is a splendid one to beholdDave K. is a splendid one to beholdDave K. is a splendid one to beholdDave K. is a splendid one to beholdDave K. is a splendid one to beholdDave K. is a splendid one to beholdDave K. is a splendid one to behold
Re: Programming tricks (and former trade secrets)

Quote:
Originally Posted by WesleyC View Post
Thanks for the notes!

I'm coming from a PHP background--all math is given equal precedence in PHP; you use parenthesis to emphasize certain points to be performed first--also, all expressions are evaluated before math is performed.

Also, one thing you must be careful of when using this particular phrase is that the input variable must either be an int or typecast to an int before performing math. If "input" is a char, the math will overflow the size of the type, creating... shall we say, "undesirable" results.
Without disagreeing with the comment about type casting...

If the compiler is really standards compliant, objects or expressions of rank less than int (such as unsigned char) are converted to int (if int can represent all values of the original type) or unsigned int (otherwise); this is known as integer promotion.

In the case of multiplying two unsigned chars, the the product of two values of unsigned type will be reduced according to the range of values for that type.

This is an area where compiler's behavior will sometimes vary, especially those targeted towards 8 bit native platforms (such as the PIC18) where math with 8 bit variables is not always evaluated as an integer (which in this case is 16 bits).

Not all compilers correctly perform integer promotion, and I've only run across one that did not behave any better when type casts were applied.

In the case of the PIC18 compiler it does understand integer promotions, however the default behavior is to not do it. The C compiler documentation covers this in section 2.7 (ISO DIVERGENCES).
__________________
--Dave