问题描述
如果我有一个 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)
并抑制编译器警告:
if (i>=0 && (size_t)i == s)
这篇关于比较 int 和 size_t的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!