1
func(int n)
// the function should return the sum of the first n term of the 
// harmonic series (1/1 + 1/2 + 1/3 + ... + 1/n )

double sumover(int n)
{
    if (n == 0)
        return 0;
    else
    {
        return (1. / n) + sumover(--n);  // here is the bug
    }
}

When the function is called with n = 1, I am expecting it to compute 1. / 1 + sumover(0) = 1 / 1 + 0

However, it's computing 1./0 + sumover(0) , why?

273K
  • 29,503
  • 10
  • 41
  • 64
  • This is also undefined behaviour (the assignment in `--n` is unsequenced relative to the read in `1. / n`) – M.M Apr 03 '20 at 04:46

1 Answers1

3
return (1. / n) + sumover(--n);

There is no guarantee that the term (1. / n) will be calculated before sumover(--n).

The standard doesn't specify that.

Hence the second term may be calculated firstly, then (1. / n) becomes (1. /(n - 1)) and then you get an unexpected output.

Replace it by

return (1. / n) + sumover(n - 1);
asmmo
  • 6,922
  • 1
  • 11
  • 25