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.

not..
the integer (primitive) can only store the values between (borders included)
-2147483648 <-> 2147483647
so, it can impossibly contain the absolute value for -2147483648, unless you use a larger numerical type.

when I asked whether that was what you ment, you answered 'sort off', so we assumed you did mean that.

EDIT: Also, saying "it is covered in our second lecture" doesn't mean that much to us.

Edited 5 Years Ago by stultuske: n/a

stultuske appears to be right, this was my initial thought too. Otherwise, the logic is so basic that there really can't be any other error.

Mathematically anything below zero * -1 is the positive version of that number, thats indisputable. In the case of all of the positive numbers, i am highly doubtful that passing back a parameter without modifying it at all would herald a mistake.

To be sure I ran a loop from MIN_VALUE to MAX_VALUE and printed an error if the return value was less than 0 (i.e. a mistake had happened) and like stultuske said, the only error came from the first iteration, which returned itself, a negative number.

If there is some other error, it's not just subtle, it's an absolute ninja.
(absolute.. see how i did that? ;)

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.

Well ....
I'm still curious into what the error in this code is.
could you enlighten us about it?

This article has been dead for over six months. Start a new discussion instead.