Click to See Complete Forum and Search --> : conversion of values when typecasting


villemos
October 31st, 2002, 01:28 AM
Hey,

Yes, I know; Don't typecast!

But I came across an example in connection with another thread, where the properties of the typecast is used. Now, I get scared when I start to use the inplicit properties of C++ to get functionality.

So can anyone tell me if there are excact convensions for converting when typecasting, or if it is platform/compiler/vendor/whatever specific?

For example if I have

float value(1.99);
int integer = (int) value;

can I then count on "integer" always becomming 1? Will the decimal always just be stripped away or will some clever rounding be attempted somehwere (when the customer is standing with all the big bosses) and suddenly integer is 2?

Cheers,
villemos

BaroloMan
October 31st, 2002, 06:53 AM
The C++ ARM specifies that conversion of a floating point value to an integral type truncates. The accuracy of a floating-point implementation varies from processor to processor and from precision (float versus double versus long double).

The precision is quite accurate in the case of 1.99. That will always be truncated to 1. The most common truncation error is getting the integral representation of an "exact" floating-point number such as 21.0 or 100.0. This is because not all integers can be exactly represented in floating-point. For example, the underlying value of a float 100 could be 99.999998. The expression

int i = 100.0f

would yield a result of 99 because of truncation.

What programmatically will work is to "bias" a floating point value to guarantee proper truncation. Consider the following trivial code:

float f;
// ... code modifies f
int i = f + 0.5;

One item of concern is negative numbers. According to the ARM, the direction of truncation of negative numbers varies from machine to machine. One machine may interpret (int) -2.5 = -2, whereas another machine may interpret it as -3. You can write portable software by managing the sign of the numbers and allowing all truncations to occur on positive numbers only.

I hope this helps.

villemos
October 31st, 2002, 06:59 AM
Sure did. Thanks a lot.

villemos.