-1

I have the following code snippet:

cout << indexCoveredA[a.size()-1] << " "<< b.size()-1 << endl;
if (indexCoveredA[a.size()-1] < (b.size() - 1) ) {
  cout << "entered";
}

Where a, b, indexCoveredA and indexCoveredB are std::vector<int>.

When I run this code, the console prints:

-1 4

This means that in the if condition, LHS is less than RHS. However "entered" is not printed, which means that the if condition is evaluated to be false.

Now if I change the condition to (indexCoveredA[a.size()-1] + 1 < b.size() ), then "entered" is printed in the console.

I have tried this out with MSVC and minGW compilers. I am not able to understand why this is so.

Can someone please explain?

Thanks.

Abhishek Bansal
  • 12,589
  • 4
  • 31
  • 46

1 Answers1

6

The type of indexCoveredA[] is int, but the type of b.size() is an unsigned type (whatever size_t is, likely either unsigned int or unsigned long long).

As a result, this comparison gets performed as an unsigned comparison. As an unsigned number, -1 looks much larger than 4.

You can try this example to demonstrate to yourself:

#include <iostream>

int main()
{
    int i = -1;
    unsigned u = 4;

    if (i < u)
    {
        std::cout << "less" << std::endl;
    } else
    {
        std::cout << "not less" << std::endl;
    }
}

This prints not less.

If I compile with G++ and warnings enabled, I get the following warning that hints at the problem:

x.c: In function ‘int main()’:
x.c:8: warning: comparison between signed and unsigned integer expressions

You might turn warnings on for your compiler.

Joe Z
  • 17,413
  • 3
  • 28
  • 39