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.

you mean by running it on the smallest possible int value
-2147483648
?

sorta so how will it be fixewd

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.

Member Avatar for hfx642

Well... That's NOT a "Bug".
That's a limitation!

yea didnt say that was the answer there is a bug find it

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.

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?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.