[Mingw-users] convert double to int: same gcc, but different result on MinGW vs Ubuntu?

Back to archive index

KHMan keinh****@gmail*****
Thu Mar 1 11:05:03 JST 2018


On 2/16/2018 5:36 AM, John Beale wrote:
> [snip]
> I am using the MINGW32 shell and gcc -v reports (MinGW.org 
> GCC-6.3.0-1) 6.3.0

I can get different results (44/45) using the same compiler 
running different settings. Here are some -S outputs.

-O2 will optimize away the divide at compile time:

	movl	$45, 4(%esp)
	movl	$LC0, (%esp)
	call	_printf
	leave

-O0 will either use x87 instructions (80 bits precision 
internally) or SSE2 (64 bits) depending on other options:

	fldl	LC0
	fstpl	56(%esp)
	fldl	LC1
	fstpl	48(%esp)
	fldl	56(%esp)
	fdivl	48(%esp)
	fnstcw	30(%esp)
	movzwl	30(%esp), %eax
	movb	$12, %ah
	movw	%ax, 28(%esp)
	fldcw	28(%esp)
	fistpl	44(%esp)
	fldcw	30(%esp)

The x87 control word is changed. The $12 is for setting RC=11 
(truncate). Then FISTPL will convert with truncation. And you may 
get a 44 as the result. At -O2, changing a and b to volatile gets 
me 44 too. Different precisions (64 vs 80) may give you slightly 
different results (1 ULP or so) and then truncate, boom.

There are gcc math options and math library features that we can 
play with, but IMHO relying on them in this case is the wrong 
solution. Prefer robust over fragile techniques.

Please get expert guidance if you are unsure of these things.


> CODE: SELECT ALL 
> <https://www.raspberrypi.org/forums/viewtopic.php?f=63&t=205567#>
> 
> |#include <stdio.h> void main() { double a = 4.5; double b = 0.1; 
> int i = a / b; printf("%d\n",i); }|
> 
> Ubuntu 16.04 on VirtualBox/Win10 result: 45
> Raspberry Pi Raspbian (ARM)          result: 45
> Online compiler demo: at www.onlinegdb.com/online_c_compiler 
> <https://www.onlinegdb.com/online_c_compiler> : 45
> MinGW32 gcc 6.3.0-1 result: 44


-- 
Cheers,
Kein-Hong Man (esq.)
Selangor, Malaysia




More information about the MinGW-Users mailing list
Back to archive index