Strange behaviour of if | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

Strange behaviour of if

Could you, please, explain to me how can be -6 more than 100001? Why is the output of this code as it is? Is it something with signed/unsigned comparison? How to fix the problem? Thanks for help.

5th Jun 2018, 5:48 PM
2 Answers
+ 10
size returns an unsigned int so your -6 is converted to unsigned int for the compare becoming the bigger number. Use: if (i>=(int)fin.size()) to force the signed compare.
5th Jun 2018, 6:01 PM
John Wells
John Wells - avatar
+ 3
The size() method returns a value of std::size_type, a data type that cannot take negative values (which makes sense since a containers size cannot be less than 0). In order to compare the two values, the compiler casts i from int to std::size_type by flipping all bits, leaving a way higher binary value than 100001.
5th Jun 2018, 6:04 PM
Shadow - avatar