takmicenjesutra's blog

By takmicenjesutra, 10 years ago, In English

Take a look at the following code:

#include <cstdio>
#include <set>

using namespace std;

set<int> s;

int main()
{
    printf("%d", s.size() > -1);
    return 0;
}

Output is 0, but it should be 1 (obviously s.size() = 0 > -1). Code is tested on ideone and codeforces compilers. Can somebody explain this?

  • Vote: I like it
  • -12
  • Vote: I do not like it

»
10 years ago, # |
  Vote: I like it +8 Vote: I do not like it

s.size() returns an unsigned value. When you compare it to signed -1, -1 is promoted to an unsigned value too and becomes SIZE_MAX. Then s.size() > SIZE_MAX yields false.

»
10 years ago, # |
  Vote: I like it +3 Vote: I do not like it

Your code is equivalent to this:

#include <iostream>

using namespace std;

int main()
{
    unsigned a = 0;
    int b = -1;

    cout << ( a > b );

    return 0;
}

b is casted to unsigned and becomes greater than 0 so there is no bug in the compiler.

»
10 years ago, # |
  Vote: I like it +3 Vote: I do not like it

try this:

printf("%d", (int)s.size() > -1);