This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Calling a function with a float argument modifies caller's state.


On 22/08/2012 15:58, Jeff B wrote:

On 08/21/2012 06:40 PM, Jeff B wrote:


(int)floatVarA = 0.000000 <<=== initial value 0??
On 08/22/2012 03:50 AM, Andrew Haley wrote:

The initial value is zero because there is garbage in Float Register 0.

floatVarA = 1234.000000
Now Float Register 0 contains 1234.0 .

(int)floatVarA = 1234.000000 <<=== changed
Which gets printed out.

floatVarB = 5678.000000
Now Float Register 0 contains 5678.0 .

(int)floatVarA = 5678.000000 <<=== changed again
Which gets printed out.

floatVarA = 1234.000000
etc...

Moral: undefined behaviour can do anything.

Andrew.


OK, then I guess the presence of the cast makes it OK for the compiler
to pull the bits for a variable from somewhere other than where the
variable actually is.

So, while we are at it, what other casts should I avoid?

Thanks.


You are still missing the point.


Avoid writing code with undefined behaviour. Do not lie to your compiler. Do not tell it "here is a float" and pass it an integer. Use "-Wall" to let the compiler help you avoid such mistakes.

It is perfectly okay to cast a float to an int - but it is not okay to do so and then expect the compiler to treat it as a float. So you can write this:

printf("(int) floatVarA = %d\n", (int) floatVarA);

Then you are casting the float to an int legally (1234.0 will turn into 1234), then passing that int to printf, with a format string that tells printf to expect an int and print it out.



Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]