help-gplusplus
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Division in C++


From: Onno Garms
Subject: Division in C++
Date: 11 Jul 2005 10:50:08 -0400

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;
  }
}

Can anybody explain why this hangs?

What I want the program to do in the loop is the following:
1. compute a/b
2. compute a/b again
3. compare to previous result
4. see that it is the same and break the loop

However the program runs in an endless loop.

Regardless of any rounding errors, a/b should always return
the same value, shouldn't it?

Experiments:
- Storing the result of the second computation in another
  variable d and then comparing d to c works correctly.
- if (static_cast<double>(a/b)<=c)
  endless loop
- Finally, the program below prints "not yet" (and nothing
  else):
  while (1)
  {
    c = a/b;
    if ((d=a/b)<=c) break;
    std::cout << "not yet\n";
    if (d<=c) break;
    std::cout << "but now\n";
  }

Does the gnu compiler apply "optimizations" that cause the
behaviour? Which ones? (I compile without options.)

Or what else causes this strange behaviour?

Greetings,
Onno
[This is a small enough loop that I'd just look at the assembler code.
-John]


reply via email to

[Prev in Thread] Current Thread [Next in Thread]