IF statement does not evaluate properly

I have a very odd situation that I hope someone can shed some light on:

mResults is std::vector<int>
mMaxListLength is int.
mTest is int.

1
2
3
4
5
6
7
8
9
10
11
12
if (!mResults.empty())
{
	for (int i = mResults.size()-1; i >= 0; --i)
	{
		mTest = mResults.size() - mMaxListLength;
		if (i >=  mTest)
		{
                 //  some code;
                }
         }
}
      


This works.


1
2
3
4
5
6
7
8
9
10
if (!mResults.empty())
{
	for (int i = mResults.size()-1; i >= 0; --i)
	{
		if (i >=  (mResults.size() - mMaxListLength))
		{
                 //  some code;
                }
         }
}


This does not.

The first snippet of code evaluates as expected however the 2nd does not evaluate as True when it should, and skips the "some code" part...

I am confused. Please help!
Thanks
Paul

Last edited on
The problem is this expression mResults.size() - mMaxListLength
mResults.size() is of unsigned type and at least as big as int so the result will be unsigned. If mResults.size() < mMaxListLength the result will wrap around and you get a very big value.

In the first code you assign that value to the int variable mTest so the value is converted into a signed value and happens to be correct as you want it.

In the second code you are comparing a signed value with the unsigned value. Before the comparison take place the signed value is converted into an unsigned value. It doesn't make much difference that i is converted to unsigned here because it will always be positive on that line. The problem is that you compare i with the large unsigned value you got from mResults.size() - mMaxListLength.
Last edited on
Makes sense. Thanks Peter.
Topic archived. No new replies allowed.