2

Only the first statement is printed even though both if expressions should evaluate the same. Why?

    map <int, int> elem;
    vector <int> nums(2);
    int x = 1;
    elem[x]=-1;
    
    int val = elem[x];

    if(val>nums.size()/3) {cout << "First";} // as you can see, vals is -1 and nums.size() is 2
        
    if(-1>2/3) cout<< "Second";
Spade
  • 65
  • 5
  • 2
    `nums.size()` isn't an `int` – Swift - Friday Pie Sep 23 '20 at 01:41
  • If you are not asking for help with a compilation error, it's a good idea to make sure your example code compiles [without warnings](https://stackoverflow.com/questions/57842756/why-should-i-always-enable-compiler-warnings). – JaMiT Sep 23 '20 at 03:56

1 Answers1

3

They are not the same.

if(val > nums.size() / 3) {

The problem is that num.size() has type of size_t which is unsigned. When you compare signed to unsigned type, you get undefined behaviour.

If you really want to make it the same, then you need to do a cast:

if (val > static_cast<int>(nums.size()) / 3)

now it would be similar to your second code

if(-1 > 2 / 3)

both of which would result in false and you should not see any First or Second printing.

artm
  • 17,291
  • 6
  • 38
  • 54