Your function only performs a pointer conversion. A function call of the form
q = function(p); /* p is a "const int *" pointer,
q is assignment comaptible with "float *". */
can be replaced by the expression:
q = (float *) p;
by itself, this doesn't do any harm. The problem is elsewhere in your program.
Note that most type punning, like accessing an object of type int
using an expression of type float
via pointers, is undefined behavior in the C language. This isn't going on in the example code, but things are headed in that direction; the pointer is probably being prepared for carrying out type punning.
Consider that int
and float
don't necessarily even have the same size; and that is not the only consideration. In code like this:
int i = 42;
/* now treat i as a float and modify it sneakily */
*((float *) &i) = 3.14;
printf("i = %d\n", i);
the output of the printf
can still be 42. The optimizing compiler can put i
into a machine register, whereas the sneaky assignment might be performed on the memory location that serves as the "backing storage" for i
, and so i
appears unchanged since the printf
call uses the register-cached copies. The compiler is not required to consider that a modification of an object designated by the type float
might affect the value of an object of type i
(even if they otherwise have the same size, so there is no collateral damage done by the assignment, like overwriting other objects).
In the real world, sometimes it is necessary to write a code that manipulates floating-point objects as if they were integers: typically unsigned int
integers, to gain access to the bitwise representation of the float
. When this is done, you have to use unions, or perhaps compiler-specific features, like GCC's -fno-strict-aliasing
option which causes the compiler to optimize more cautiously in the face of type punning. in that kind of code, you make sure that the assumptions are all warranted about the sizes of types and such, with #ifdef
-s for different platforms, perhaps based on values pulled from running configured scripts to detect platform features.
Needless to say, this is not a good way to be learning C at a beginner level.