Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't size_t be directly compared with negative int?

Tags:

c++

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?

like image 395
cxs1031 Avatar asked Dec 25 '22 08:12

cxs1031


1 Answers

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.

like image 69
Jacob Panikulam Avatar answered Dec 28 '22 10:12

Jacob Panikulam