View Single Post
  #5   Spotlight this post!  
Unread 25-01-2007, 02:17
TimCraig TimCraig is offline
Registered User
AKA: Tim Craig
no team
 
Join Date: Aug 2004
Rookie Year: 2003
Location: San Jose, CA
Posts: 221
TimCraig is a splendid one to beholdTimCraig is a splendid one to beholdTimCraig is a splendid one to beholdTimCraig is a splendid one to beholdTimCraig is a splendid one to beholdTimCraig is a splendid one to beholdTimCraig is a splendid one to behold
Re: Typecasting Resources

Quote:
Originally Posted by brianafischer View Post
Please post more info/examples on this topic if you can!
The simplest example I can think of is:

char x = 65;
char y = 66;

char a;
int b;

/* a is not large enough to hold 131 even if the arithmetic did what was expected. a equals -125. */
a = x + y;

/* b = large enough to hold 131 but the arithmetic will still be done as above since the compiler doesn't look at the left side of the equation. */
b = x + y;

/* Force the arithmetic to be done in 16 bits by casting one of the members */

/* a still can't hold 131 but the compiler should issue a warning for loss of precision if the warning level isn't high enough. ALWAYS set the warning level as high as possible! */
a = (int) x + y;

/* This gets rid of the warning but is still wrong. */
a = (char) ((int) x + y);

/* The "correct" way to do it. b = 131 */
b = (int) x + y;