Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

comparing int with size_t

Tags:

c

casting

People also ask

Can I compare Size_t and int?

It is okay to compare a size_t value with an int value, the int value will be implicitly converted to unsigned type. Some compilers will issue a warning when you mix signed and unsigned types in comparisons.

Can you add Size_t to int?

It will get promoted to type int because type int can represent all values of type size_t and rank of size_t, being a synonym for unsigned short, is lower than the rank of int. Since the maximum values of size_t, and int are the same, the computation causes a signed overflow, causing undefined behavior.

Is Size_t always unsigned int?

No. size_t can and does differ from unsigned int .

Why do we need Size_t?

Using size_t appropriately can improve the portability, efficiency, or readability of your code. Maybe even all three. Numerous functions in the Standard C library accept arguments or return values that represent object sizes in bytes.


It's safe provided the int is zero or positive. If it's negative, and size_t is of equal or higher rank than int, then the int will be converted to size_t and so its negative value will instead become a positive value. This new positive value is then compared to the size_t value, which may (in a staggeringly unlikely coincidence) give a false positive. To be truly safe (and perhaps overcautious) check that the int is nonnegative first:

/* given int i; size_t s; */
if (i>=0 && i == s)

and to suppress compiler warnings:

if (i>=0 && (size_t)i == s)

If you're going to compare an int type to size_t(or any other library type), you are doing a risky comparison because int is signed and size_t is unsigned, so one of them will be implicitly converted depending on your compiler/platform. The best thing to do, is to rewrite your int i as:

decltype(y.size()) i = 1;

This assigns your i as the safe type you're trying to compare, and I think it's good practice. This solution is useful in all types of iterators as well. You generally don't want to trust the compiler to cast for you, you can, but it's risky, and an unnecessary risk.


size_t is going to be some sort of integer type (although possibly unsigned, so it might generate a warning) so the appropriate casting should be done for you automatically.

As others have already said, you may want to revisit whatever calculation is producing the int and see if you can do it in size_t in the first place if you're computing a required size for something.