cxs1031
cxs1031

Reputation: 170

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

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?

Upvotes: 6

Views: 5128

Answers (2)

Jacob Panikulam
Jacob Panikulam

Reputation: 1218

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.

Upvotes: 10

AnT stands with Russia
AnT stands with Russia

Reputation: 320541

Because size_t is unsigned and int is signed. Language has special rules for such "mixed" comparisons, as well as for "mixed" arithmetic. In this case these rules say that everything should be converted to size_t. Conversion to size_t, which is unsigned, distorts the original value of the int rather drastically (-1 becomes SIZE_MAX), which is what causes the "strange" result in the second case.

In the first case you forcefully convert size_t to int, thus turning your comparison into int vs. int one. It behaves in expected fashion.

Note, BTW, that std::string::size() returns std::string::size_type, which is an unsigned type, but not necessarily size_t.

Upvotes: 5

Related Questions