同为size_t比较INT [英] comparing int with size_t
问题描述
如果我有一个int和一个为size_t变量,我可以比较它们,如:
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?
推荐答案
它的安全提供的 INT
是零或正值。如果是负的,而为size_t
等于或更高级别的比 INT
,那么 INT
将被转换为为size_t
等其负面价值将反而成为正值。然后,这个新的积极的价值是相对于为size_t
值,它可以(在一个惊人的巧合不太可能)给假阳性。要真正安全的(也许是缩手缩脚)检查 INT
非负第一:
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)
和共进晚餐preSS编译器警告:
and to suppress compiler warnings:
if (i>=0 && (size_t)i == s)
这篇关于同为size_t比较INT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!