One bug in my program is caused by directly comparing size_t
with int
.
A toy sample code is as follows:
string s = "AB";
cout << (-1 < 8888888+(int)s.size()) << endl;
cout << (-1 < 8888888+s.size()) << endl;
The output is:
1
0
So why can't size_t
be directly compared with negative int
?
size_t
is unsigned, and can thus only express positive numbers. Comparing it to a negative will have wacky results.
If you try casting the int
(-1) as a size_t
, you'll find that it becomes an enormous number, which explains the behavior you are having.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With