Re: Division in C++

Antoun Kanawati <>
12 Jul 2005 05:11:48 -0400

          From comp.compilers

Related articles
Division in C++ (Onno Garms) (2005-07-11)
Re: Division in C++ (Antoun Kanawati) (2005-07-12)
Re: Division in C++ (Marcin 'Qrczak' Kowalczyk) (2005-07-12)
Re: Division in C++ (Michael Tiomkin) (2005-07-12)
Re: Division in C++ (2005-07-12)
Re: Division in C++ (Florian Weimer) (2005-07-12)
Re: Division in C++ (Gabriel Dos Reis) (2005-07-12)
Re: Division in C++ (Marcin 'Qrczak' Kowalczyk) (2005-07-12)
[2 later articles]
| List of all articles for this month |

From: Antoun Kanawati <>
Newsgroups: comp.compilers,
Date: 12 Jul 2005 05:11:48 -0400
Organization: Compilers Central
References: 05-07-046
Keywords: C++,arithmetic
Posted-Date: 12 Jul 2005 05:11:48 EDT

Onno Garms wrote:
> Hello,
> I have a short sample program that hangs on one of my
> computer when I compile in debug mode. The program works
> fine on my other computers or if I compile optimized.
> The problematic computer and compiler are quite old (gcc2.95
> on a Pentium PC running Linux), but I wonder if the problem
> will occur with other compilers on other computers if I
> change the numbers.
> Here is the code:
> int main ()
> {
> double a = 96.03755458500125997;
> double b = 3.0;
> double c;
> while (1)
> {
> c = a/b;
> if (a/b<=c) break;
> }
> }

The floating point registers are 80-bits wide, while 'double' is 64-bits
wide. If you compile, without optimization, the variable 'c' holds
the result of division, truncated to 64-bits. So, in the conditional
the following happens:

repeat the division, and hold the 80-bits result
load the value of 'c' and extend to 80-bits
compare the above two values.

Since 'c' was truncated to 64-bits and then extended to 80, it will
appear to be smaller than the untruncated result, and the comparison

However, if you swith to 'long double', you get sufficiently many bits
stored in 'c', and the program behaves are you expected.

BTW, using gcc 3.4.2 with -O3 on the above program, you get a main
function that does nothing:

pushl %ebp
movl %esp, %ebp
subl $8, %esp
andl $-16, %esp
subl $16, %esp
xorl %eax, %eax
A. Kanawati

Post a followup to this message

Return to the comp.compilers page.
Search the comp.compilers archives again.