when negation... isn't

Started by
13 comments, last by GameDev.net 17 years, 7 months ago
C++ Challenge: Can this function ever return true? If so, how?

bool test(int i)
{
    return (i != 0 && i == -i);
}
Advertisement
I don't logically see how that's possible.
daerid@gmail.com
Yes - assuming a 32-bit int, test(0x80000000) returns true. This is because while -(2^31) can be expressed in a 2's complement 32-bit quantity, 2^31 cannot, so the negation overflows.
It's an artifact of the 2's complement representation used in the microprocessor, not so much C/C++ itself. I don't know of anything in particular in the C++ standard that would prohibit non-2's complement architectures, but maybe there's something.

Try it yourself. See what's returned from test(MIN_INT).

It's because (say for 8-bit integers) they can range from -128 to +127. If you try and take the negation of -128, you can't because +128 is not representable. Binary-wise, you get -128 again.
Quote:Original post by etothex
It's an artifact of the 2's complement representation used in the microprocessor, not so much C/C++ itself. I don't know of anything in particular in the C++ standard that would prohibit non-2's complement architectures, but maybe there's something.


C's standard requires sign-magnitude, 1's complement, or 2's complement representation for signed integers. I would guess a similar requirement is in C++. I think only sign-magnitude avoids this problem.
1's complement does it okay, too; the only representation with the problem is 2's complement, because the positive and negative ranges don't match.
Oh, and alternate solution:

#define -
Quote:Original post by Sneftel
Oh, and alternate solution:

#define -


Good god man, that's evil incarnate.
daerid@gmail.com
Quote:Original post by Anonymous Poster
Quote:Original post by etothex
It's an artifact of the 2's complement representation used in the microprocessor, not so much C/C++ itself. I don't know of anything in particular in the C++ standard that would prohibit non-2's complement architectures, but maybe there's something.


C's standard requires sign-magnitude, 1's complement, or 2's complement representation for signed integers. I would guess a similar requirement is in C++. I think only sign-magnitude avoids this problem.

Not explicitly. Although there are some other requirements that might make certain alternative representations illegal.

CM
Quote:Original post by daerid
Quote:Original post by Sneftel
Oh, and alternate solution:

#define -


Good god man, that's evil incarnate.

Oh...heh. I thought his post got cut short before the actual solution. That is clever.

Thinking about it...I could do that in much of my code and still have it compile. Things like --i and i -= 5 won't cause syntax errors on their own [although the latter might lead to a missing assignment operator], and how often do you subtract, really?

CM

This topic is closed to new replies.

Advertisement