[英]comparing int with size_t
If i have a int and a size_t variable,can i compare them like:如果我有一个 int 和一个 size_t 变量,我可以像这样比较它们:
int i=1;
size_t y=2;
if(i==y)
// do something..
or i have to type-cast one of them?或者我必须对其中之一进行类型转换?
It's safe provided the int
is zero or positive.只要
int
为零或正数,它就是安全的。 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.如果它是负数,并且
size_t
的等级等于或高于int
,则int
将转换为size_t
,因此其负值将变为正值。 This new positive value is then compared to the size_t
value, which may (in a staggeringly unlikely coincidence) give a false positive.然后将这个新的正值与
size_t
值进行比较,这可能(以极不可能的巧合)给出误报。 To be truly safe (and perhaps overcautious) check that the int
is nonnegative first:为了真正安全(也许是过于谨慎),首先检查
int
是否为非负:
/* 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.如果您要将 int 类型与 size_t(或任何其他库类型)进行比较,那么您将进行有风险的比较,因为 int 是有符号的,而 size_t 是无符号的,因此其中之一将根据您的编译器/平台进行隐式转换。 The best thing to do, is to rewrite your int i as:
最好的办法是将你的 int i 重写为:
decltype(y.size()) i = 1; 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.这将您的 i 指定为您要比较的安全类型,我认为这是一种很好的做法。 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. size_t
将是某种整数类型(尽管可能是无符号的,因此它可能会生成警告),因此应该自动为您完成适当的转换。
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.正如其他人已经说过的那样,您可能想要重新访问生成
int
任何计算,并首先查看是否可以在size_t
中执行它,如果您正在计算某物所需的大小。
It is okay to compare a size_t
value with an int
value, the int
value will be implicitly converted to unsigned
type.可以将
size_t
值与int
值进行比较, int
值将隐式转换为unsigned
类型。
Some compilers will issue a warning when you mix signed
and unsigned
types in comparisons.当您在比较中混合有
signed
和unsigned
类型时,某些编译器会发出警告。 In that case you can explicitly convert the signed
value to an appropriate unsigned
type to suppress the warning.在这种情况下,您可以将有
signed
值显式转换为适当的unsigned
类型以抑制警告。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.