This is a frighteningly subtle bug I first learned about in C (Andrew Koenig's ``C Traps and Pitfalls''), but it's still with us in Java, and I assume C++ as well...
The following method looks like it should always return the absolute value of n, but every once in a while it returns the wrong answer. Spot the bug:
static int absVal(int n)
{
if (n < 0)
{
return (n * -1);
}
else
{
return (n);
}
}
bug
Solution in a couple days. Hint: The error is simple (covered in our second lecture), but not at all obvious.