If i have a int and a size_t variable,can i compare them like:
int i=1;
size_t y=2;
if(i==y)
do something..
or i have to type-cast one of them?
If i have a int and a size_t variable,can i compare them like:
int i=1;
size_t y=2;
if(i==y)
do something..
or i have to type-cast one of them?
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.
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. In that case you can explicitly convert the signed
value to an appropriate unsigned
type to suppress the warning.
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)