Calling a function with a float argument modifies caller's state.
Ángel González
keisial@gmail.com
Tue Aug 21 15:54:00 GMT 2012
On 21/08/12 08:40, David Brown wrote:
> On 20/08/2012 22:21, Jeff B wrote:
>> (...)
>>
>> WHY is a 32-bit float passed to a function in a manner different from a
>> 32-bit int???
>>
>
> A 32-bit float and a 32-bit int are completely different things. The
> fact that the have a common size is just coincidence. The compiler
> can treat them totally differently - on many targets (including, I
> believe, the x86 - depending on the compiler flags) they will be
> passed around in different registers. If it suits the cpu in
> question, the compiler can happily convert the 32-bit float to a
> 64-bit (or even higher) resolution before passing it around. You
> certainly cannot rely on being able to convert randomly between ints
> and floats while keeping the same exact values.
>
> When passing data into printf(), the compiler can take the actual
> format string into account. When you write "printf("%f", x)", you are
> /not/ saying "pass a 32-bit value x, treat it as representing a float,
> and print it". The compiler may /choose/ to treat it that way. But
> it can also validly interpret it as "treat the value x as a float, and
> print it out". When you use C properly, according to the
> specifications of printf, these do the same thing - but one way might
> do it with smaller or faster code, or with better static error
> checking. When you break C rules by your mixed casting, they can mean
> different things.
>
>> I also think that it is a really bad idea to have undocumented side
>> effects
>> like that. Or did I already say that?
>>
>
> I think most people will agree that undocumented side effects are a
> bad idea. But your program does not demonstrate undocumented side
> effects.
>
> Your program demonstrates that when you write code that has undefined
> behaviour, it does not work as you expect. That should not be a big
> surprise.
>
> You also don't demonstrate that the calls to printf are modifying the
> caller's state. My immediate interpretation of your result is that
> the compiler is doing alias analysis - it knows what can and cannot be
> legally done in conversions between unrelated types (int and float),
> and it uses this knowledge to generate code that is more optimal under
> the assumption that the programmer is following the rules of C. When
> you break those rules, you break that assumption - lie to your
> compiler and you will get bad code as a result.
>
>
> Try compiling your code with -Wall, which will help point out your
> errors.
Compiling with -Wall it will complain about passing an int to a %f
parameter.
The program shown by Jeff is consistent with printf(..., float) moving
the value to a float register and printf("%f") printing the code from
that register.
More information about the Gcc-help
mailing list