Fun with numbers - dammit, but I want a cast!

Bengt Richter bokr at oz.net
Tue Aug 12 04:41:19 CEST 2003


On Mon, 11 Aug 2003 18:32:12 -0700, Erik Max Francis <max at alcyone.com> wrote:

>Carl Banks wrote:
>
>> It seems you didn't read what I wrote carefully.  I was talking about
>> C, not C++.  Neither I nor the post I replied to mentioned C++ once.
>> I mentioned the C standard several times, never the C++ standard.
>> 
>> Type casts in C are as I described.
>
>C++ was mentioned by the original poster; either way, C and C++ casts
>act precisely the same in this context.  (float) 1 and *(float *) &i
>have precisely the same meanings both in C and C++.
>
<nit>With (float) 1 it can optimize to one instruction with immediate
operand constant. With the other it needs (at least on x86) to move via
EAX, for two instructions (e.g., assigning the resp values).

Where x&y are extern floats, to make sure unused vars don't get optimized away:

; 3    :     int i = 1;

  00004	c7 45 fc 01 00
	00 00		 mov	 DWORD PTR _i$[ebp], 1

; 4    :     x = (float) 1;

  0000b	c7 05 00 00 00
	00 00 00 80 3f	 mov	 DWORD PTR _x, 1065353216 ; 3f800000H

; 5    :     y = *(float *) &i;

  00015	8b 45 fc	 mov	 eax, DWORD PTR _i$[ebp]
  00018	a3 00 00 00 00	 mov	 DWORD PTR _y, eax


I agree the bits are just being moved in either case for assignment. But
then if you multiply by 5.0, the compiler will fold one constant expression,
but not the other (even with max optimizimg and declaring const stuff not shown here)

; 3    :     int i = 1;

  00004	c7 45 fc 01 00
	00 00		 mov	 DWORD PTR _i$[ebp], 1

; 4    :     x = 5.0*((float) 1);

  0000b	c7 05 00 00 00
	00 00 00 a0 40	 mov	 DWORD PTR _x, 1084227584 ; 40a00000H

; 5    :     y = 5.0*(*(float *) &i);

  00015	d9 45 fc	 fld	 DWORD PTR _i$[ebp]
  00018	dc 0d 00 00 00
	00		 fmul	 QWORD PTR __real at 8@4001a000000000000000
  0001e	d9 1d 00 00 00
	00		 fstp	 DWORD PTR _y

</nit>

So what a source spelling "really means" depends on what aspect you are concentrating,
I think you might agree? Sometimes the context does not result in code that will
"act precisely the same." Depending ;-)

Regards,
Bengt Richter




More information about the Python-list mailing list