I am writing this because I have really no idea why this is happening. I know how to correct it/go around it but what I would like to know is the reason this occurs. I am using C and my compiler is gcc 4.4.1 (TDM) running on an Intel machine.
Assumptions about floats: -Conform to the IEEE 754 standard
– Are stored in a Big Endian way
Let’s assume we have a function taking in an array of 4 bytes and returning them as a float. That is the goal of the function. Let’s also say that for example all the function will do is get the bytes in the “right order” and since the system is little endian it will just swap them and put them into the float to return a value. For simplicity’s sake I don’t include any checks for NaN or INF since this is not the purpose of this question.
float testFunction(char* arr)
{
//this will be the float we return
float ret;
//let's just get a char pointer to the float so we can alter its byte values
char* c = (char*)&ret;
//just swap them so they conform with little endian byte order
c[0] = arr[3];
c[1] = arr[2];
c[2] = arr[1];
c[3] = arr[0];
//up to here if you debug and watch ret's value it is correct as it is supposed to be
return ret;
}
The problem is wherever I use the function … let’s say like below
float f = testFunction(arr);
Then the float f has a completely irrelevant float value to the bytes you pass as parameters.
The way to succesfully go around this is to declare a function that accepts the float as a parameter and give it a value inside the function like so:
void testFunction(char* arr,float* f)
{
char* c = ((char*)f)
c[0] = arr[3];
c[1] = arr[2];
c[2] = arr[1];
c[3] = arr[0];
}
But still my question is, why does this happen when I try to return the value? I do understand that float ret is a temporary value inside the scope of the function but the return statement should copy its value outside of the function. Isn’t it correct?
What am I missing? I guess it must be something really obvious.
I’ll say something stupid. But try initializing
ret, likefloat ret = 0;.I’m not sure you can initialize a variable “piecemail” one
charat a time and consider it to be “initialized” for the C standard (and the compiler)