Floating point type conversions

Questions about the BASICtools and MakeItC
YahooArchive
Posts: 1462
Joined: Fri Oct 19, 2012 5:11 am

Re: Floating point type conversions

Post by YahooArchive »

> No. C is not a typesafe language so it is easy to be fooled. What
> you are seeing here is the automatic type *conversion* that happens
> when you mix ints and chars in C.

I assume you're talking about type *promotion*? C internally promotes all
operands in an expression to the highest-ranking type that occurs within it.


> The typecasts are ignored - they
> are as redundant as saying
>
> int j = (int)i;
>
> The following generates identical code: [...]

Generated code coming out the same does not mean the cast was ignored by the
compiler, implicit promotion is context-dependent; a type cast is explicit, and
must be processed differently. And I'd have to think that identical code
generation in these cases is likely platform-dependent, maybe even
settings-dependent, padding on or off could make a difference.

More, in the case of assigning a higher-ranking type to a lower-ranking type
(e.g., char = int) the compiler would issue a warning if the cast is omitted.
Casting causes the compiler to skip the warning, and it shows the programmer's
intent to do something that could be problematic if accidental.

> The sort of situation where you need to use a typecast in C is when the
automatic conversion rules are not suitable. e.g.
>
> double pi = (double)22/7;

Ironically, that cast functions practically the same as a coersion function --
the bits definitely do not come out the same! :-)

As I think of it, the only time the bits are guaranteed to not get diddled is
when you cast an address/pointer to a pointer [to a] type and dereference it.
Then whatever bits are in memory at that location are evaluated as the type to
which the pointer was cast, e.g.,

double f = 22.0/7.0;
int *p = (int *)&f;
int i = *p;

The value of i is incoherent, but the [first 4 bytes worth of] bits are
unchanged. C won't always let you cast a value of one type to another, but it
will let you cast any address/pointer to a pointer to any other type.

-MM



Post Reply