Chief Delphi

Chief Delphi (http://www.chiefdelphi.com/forums/index.php)
-   Programming (http://www.chiefdelphi.com/forums/forumdisplay.php?f=51)
-   -   What the...? casting bug? (http://www.chiefdelphi.com/forums/showthread.php?t=27040)

gnormhurst 22-03-2004 14:02

What the...? casting bug?
 
'splain this, somebody:

Code:

#define STRAIGHT_DRIVE_DIRECTION ( 127 + 30 )
 
      static int steeringValue = 0;
      . . .
      steeringValue = (int) ((STRAIGHT_DRIVE_DIRECTION));
      printf( "nav: DTC  %3d ", steeringValue  );

That printed a value of -99! Why?

Changing the assignment to:
Code:

      steeringValue = (int) ((unsigned char) (STRAIGHT_DRIVE_DIRECTION));
made it print "157" as expected the first time.

Is this weird, or is there something about type casting I don't understand?

gnormhurst 22-03-2004 14:08

Re: What the...? casting bug?
 
Ohhhhhhh!

Funny how you understand something as soon as you post it.

The compiler takes (127 + 30) and performs signed 8-bit arithmetic, yielding -99. Casting as a signed (int) duly kept the sign: -99. Casting as an unsigned char reinterpreted the value as 157, which was then cast as a signed int: 157.

My error was in assuming that constants were treated as unsigned chars, but they are treated as signed chars.

Ryan M. 22-03-2004 14:18

Re: What the...? casting bug?
 
Quote:

Originally Posted by gnormhurst
Ohhhhhhh!

Funny how you understand something as soon as you post it.

The compiler takes (127 + 30) and performs signed 8-bit arithmetic, yielding -99. Casting as a signed (int) duly kept the sign: -99. Casting as an unsigned char reinterpreted the value as 157, which was then cast as a signed int: 157.

My error was in assuming that constants were treated as unsigned chars, but they are treated as signed chars.

That is exactly what happened. :)

Greg Ross 22-03-2004 14:20

Re: What the...? casting bug?
 
Boy, you guys are fast. :)

Norm, I think if you had used
Code:

#define STRAIGHT_DRIVE_DIRECTION ( 127u + 30 )
you would have been ok.

Astronouth7303 22-03-2004 15:49

Re: What the...? casting bug?
 
There's a compuler option for that. Project>Build Options...>Project. Go to MPLAB C18. check "Treat 'char' as unsigned" (under Category General). The command-line flag is '-k'


All times are GMT -5. The time now is 02:51.

Powered by vBulletin® Version 3.6.4
Copyright ©2000 - 2017, Jelsoft Enterprises Ltd.
Copyright © Chief Delphi