views:

221

answers:

3

try it out:

volatile float bob = -344.0f;
unsigned int fred = (unsigned int)bob;

printf("%d\n",fred);

output will be 0.

obviously I am expecting it to wrap around just as if I had cast from a signed int to an unsgined int (which does wrap and act as expected on the iphone)

we assume it is something to do with the floating point settings.

any ideas?

+6  A: 

This is to be expected - casting a negative float to an unsigned int results in undefined behaviour (UB). If you want the value to wraparound (which is also UB, BTW), then you would need to cast to a (signed) int first and then to unsigned int. Ideally you should not rely in UB at all and find a better way of doing what you need to do.

Paul R
so why is it not a problem with VC++ or the PSP compiler ?
matt
@matt: because you're relying on undefined behaviour
Paul R
@matt: It *is* a problem on those compilers if you're expecting the int to be 0, which is just as reasonable as expecting it to wrap around. That's the problem with undefined behavior: You can't reasonably expect any particular thing to happen. It could wrap around, it could go to 0, it could send suggestive emails to your employer — it's completely undefined what it will do.
Chuck
@matt: In short, you have a bug in your code.
Stephen Canon
A: 

Cast via a signed int.

Andy J Buchanan
+3  A: 

§6.3.1.4 of the C standard:

When a finite value of real floating type is converted to an integer type other than _Bool, the fractional part is discarded (i.e., the value is truncated toward zero). If the value of the integral part cannot be represented by the integer type, the behavior is undefined.

So like Paul R said, this is undefined behavior.

Stephen Canon