Can anyone explain the following codes?
especially the cast of pointer type.
What does it really mean. Thanks.
float f1;
unsigned long l1;
f1=4.5;
l1=*(unsigned long*)&f1;
It means, among other things, that the coder is trying to make his
program commit suicide.
On the surface, he is taking the address of the float f1,
using it as a pointer to an unsigned long,
and storing what ever is pointed at into an unsigned long.
Here is why this playing fast-and-loose with these types is a bad thing:
1) There is no requirement for floats to be stored in any particular
way. The same bit pattern could mean different values for f1 on
different platforms or even the same platform and a different compiler.
2) There is no requirement for unsigned longs to be stored in any
particular way. The same bit pattern could mean different values for l1
on different platforms or even the same platform and a different compiler.
1 & 2) together mean that you don't have a clue what it means to treat a
sequence of bits stored in a float as an unsigned long.
3) [and this is the killer] There is no requirement about the relative
amounts of space that a float and an unsigned long consume. In
particular, it would not be surprising for floats to be shorter than
unsigned longs. That means that using the address of a float as the
address of an unsigned long involves using memory which is not part of
the float object. This is a very bad thing.
This kind of code depends on a particular representation of floats, a
particular representation of unsigned longs, and on the assumption that
sizeof(float) >= sizeof(unsigned long) and probably that sizeof(float)
== sizeof(unsigned long).
This is the kind of code that should get a programmer fired in many
cases. Even if the specification of a program is, at the moment, for a
particular piece of hardware with a particular software configuration,
writing code like this depends on there never being a hardware or
software modification. This is a reasonable bet for embedded software
at best.