This is the mail archive of the
gcc-bugs@gcc.gnu.org
mailing list for the GCC project.
overflow exception
- From: Andrea Latina <andrea dot latina at to dot infn dot it>
- To: bug-gcc at gnu dot org
- Date: Sat, 19 Jan 2002 01:01:25 +0100
- Subject: overflow exception
hi all,
I think there is a problem with the trapping of the overflow exception
in g++ (maybe in gcc too?).
I'm using gcc version 3.0.3 on a Intel RedHat Linux 7.2, compiled giving
no options to the configure script.
When I run the attached program, which compute the factorial of an
integer number using a recursive (integer) routine and a non recursive
"exact" computation (through an exponentiation and a logarithm
extraction), I get this output:
n! = integer exact
0! = 1 1
1! = 1 1
2! = 2 2
3! = 6 6
4! = 24 24
5! = 120 120
6! = 720 720
7! = 5040 5040
8! = 40320 40320
9! = 362880 362880
10! = 3628800 3628800
11! = 39916800 39916800
12! = 479001600 479001600
13! = 1932053504 6227020800
14! = 1278945280 87178291200
15! = 2004310016 1307674368000
16! = 2004189184 20922789888000
17! = Aborted
compiling the source with:
g++ fact.cc -ftrapv -o fact
That's strange! The integer factorials over 12 are clearly wrong ('cause
of the overflow, being 13!=6227020800 > 2^32), but the program dies only
at 17!.
Shouldn't it die during the computation of 13! ?
If I compile the program without the option "-ftrapv" simply the program
goes ahead ignoring any problem, as I can expect.
I hope this report can be useful.
Thanks to all of you.
cheers,
Andrea Latina
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
static int fact(int n )
{
if (n == 0) return 1;
return n * fact(n -1);
}
static double exp_fact(int n )
{
double ln_fact = 0;
for (int i = 1; i <= n; i++)
{
ln_fact += log(double(i));
}
return exp(ln_fact);
}
int main()
{
cout << setprecision(14);
cout << setw(4) << " n! = "
<< setw(15) << "integer" << '\t'
<< setw(15) << "exact" << endl << endl;
for (int n = 0; n < 20; n++)
{
cout << setw(4) << n << "! = "
<< setw(15) << fact(n) << '\t'
<< setw(15) << exp_fact(n)
<< endl;
}
return 0;
}