0

In the test program, the size of v is 2. Since 2 is bigger than -1, I think the while loop should be entered and "!" should be printed infinetely. However, the while loop is getting skipped. Why is that? I tested the code in VS 2017 and Ideone.

#include <iostream>
#include <vector>
int main(){
    std::vector<std::pair<int,float>> v = {{1,2.0},{2,2.0}};
    std::cout << v.size();
    while(v.size() > -1){
        std::cout << "!";
    }
}
Ruirui
  • 149
  • 7
  • 1
    When I compiled the code provided, my compiler warned the comparison is always false, and that the int was being converted to unsigned long. I highly recommend you enable your compiler's warnings to raise the visibility of these kinds of easy-to-do mistakes. – Eljay Sep 03 '19 at 16:02
  • @Eljay was enabled, but no warnings regarding that – Ruirui Sep 03 '19 at 16:04
  • [c++ illogical >= comparison when dealing with vector.size() most likely due to size_type being unsigned](https://stackoverflow.com/q/12152605/995714), [Comparison size_t variable with -1 (maximum size value) in c++ code](https://stackoverflow.com/q/25094159/995714), [Why is (sizeof(int) > -1) false? (duplicate)](https://stackoverflow.com/q/34151309/995714) – phuclv Sep 03 '19 at 16:15
  • You must not have C4287 warning enabled in particular with your compiler, otherwise you would have seen the warning. – Eljay Sep 03 '19 at 16:22
  • If it doesn't warn that this is always false, then it should at least warn you of a signed/unsigned mismatch. –  Sep 03 '19 at 16:38

1 Answers1

4

When comparing unsigned type of std::vector::size_type and a signed type of int, int is converted to std::vector::size_type. -1 turns into a very large unsigned integer, which is greater than the size of the vector. Thus the while condition evaluates to false and the while body is skipped. If you turn on compiler warnings, you'll get something like:

<source>:6:20: error: comparison of integer expressions of different signedness: 'std::vector<std::pair<int, float> >::size_type' {aka 'long unsigned int'} and 'int' [-Werror=sign-compare]

    6 |     while(v.size() > -1){

      | 
Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
  • Note: Most compilers should warn you (or anyone) of things like this. –  Sep 03 '19 at 16:35
  • Sorry, I must have missed that the first time. I was more so mentioning it for the benefit of the OP, not you, but you already did mention it and I missed it. So just ignore my comment. –  Sep 03 '19 at 16:41