0

I have a strange bigger than problem.

iGhostLen is -1 and iMaxGhost is 480. But still the line iGhostLen=iMaxGhost; is hit.

Is -1 a special case or where could I have gone wrong. I don't think that -1 is bigger than 480.

Thank you.

unsigned int iMaxGhost=(120 * 4);
int iGhostLen=-1

if (iGhostLen > iMaxGhost)
{
    iGhostLen=iMaxGhost;
}
tmighty
  • 10,734
  • 21
  • 104
  • 218
  • I'm pretty sure it's because you are comparing a signed int with an unsigned int. – Chemistpp Oct 13 '13 at 19:46
  • 1
    Those warnings you see when you compile this? You may want to consider what they mean. And for bonus points, what happens when `iMaxGhost` is `unsigned short` (just to throw a wrench in the gears). – WhozCraig Oct 13 '13 at 19:46

2 Answers2

1

You should get a compiler warning because of comparing signed and unsigned integers. Change unsigned int to int, and read a bit about number representations.

erenon
  • 18,838
  • 2
  • 61
  • 93
  • Thank you. But why can the ">" statement not compare unsigned int and signed int? – tmighty Oct 13 '13 at 19:48
  • 1
    @tmighty, `unsigned int` holds more positive values than `int` and `int` more negative values. It would have to use a larger type, and reserving the largest type for only comparisons would be a bit silly, so a choice was made to make the signed value unsigned. – chris Oct 13 '13 at 19:51
  • And what do you do? In another part of my code I have the following code which also gives me a compiler warning: for ( int h = iHPStart; h < (int)uPhrase.HalfphonesInLine.size()-2; h++) { if (h == uPhrase.HalfphonesInLine.size()-2) I felt that my code was nice, but now I think it is untidy. How do you handle such situations, please? – tmighty Oct 13 '13 at 19:53
  • @tmighty signed/unsigned comparisons can get you into trouble if you're not deliberately careful about how you use them. For example, a seemingly simple for-loop such as `for (unsigned int i=N; i>=0; --i)` will run ad-infinitum on nearly all systems. Integral conversions are so important they are covered *extensively* by the language standard, and although it is akin to reading chloroform-in-print, I strongly advise you review it. – WhozCraig Oct 13 '13 at 20:00
  • I bought so many books, but I found out that I only learn by doing or by reading here, so books are not an option for me, but thank you. – tmighty Oct 13 '13 at 20:04
0

This happens because iMaxGhost is unsigned, but iGhostLen is signed. The signed value will be converted to an unsigned value for the conversion (so -1 will become an extremely large value).

You can fix this by changing iMaxGhost to be a signed integer, or by having a special case for negative values.

James M
  • 18,506
  • 3
  • 48
  • 56