我可以在C中直接比较int和size_t吗?
我可以像这样比较 int
和 size_t
变量吗:
int i = 1;
size_t y = 2;
if (i == y) {
// Do something
}
或者我是否必须键入强制转换其中一个?
Can I compare an int
and a size_t
variable like this:
int i = 1;
size_t y = 2;
if (i == y) {
// Do something
}
Or do I have to type cast one of them?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
只要
int
为零或正数,它就是安全的。如果为负数,并且size_t
的等级等于或高于int
,则int
将转换为size_t
> 因此它的负值将变成正值。然后将这个新的正值与size_t
值进行比较,这可能(极其不可能的巧合)给出误报。为了真正安全(也许过于谨慎),首先检查 int 是否为非负数:并抑制编译器警告:
It's safe provided the
int
is zero or positive. If it's negative, andsize_t
is of equal or higher rank thanint
, then theint
will be converted tosize_t
and so its negative value will instead become a positive value. This new positive value is then compared to thesize_t
value, which may (in a staggeringly unlikely coincidence) give a false positive. To be truly safe (and perhaps overcautious) check that theint
is nonnegative first:and to suppress compiler warnings:
如果您要将 int 类型与
size_t
(或任何其他库类型)进行比较,那么您将进行危险的比较,因为int
是有符号的,并且size_t< /code> 是无符号的,因此其中之一将根据您的编译器/平台进行隐式转换。最好的办法是将您的
int i
重写为:这会将您的
i
指定为您要尝试比较的安全类型,我认为这是一个很好的做法。该解决方案在所有类型的迭代器中也很有用。您通常不想相信编译器会为您进行强制转换,您可以这样做,但这是有风险的,而且是不必要的风险。If you're going to compare an int type to
size_t
(or any other library type), you are doing a risky comparison becauseint
is signed andsize_t
is unsigned, so one of them will be implicitly converted depending on your compiler/platform. The best thing to do, is to rewrite yourint i
as: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
将是某种整数类型(尽管可能无符号,因此可能会生成警告),因此应该自动为您完成适当的转换。正如其他人已经说过的那样,您可能需要重新审视生成
int
的任何计算,看看是否可以在size_t
中进行计算(如果您正在计算 a)某物所需的尺寸。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 insize_t
in the first place if you're computing a required size for something.可以将
size_t
值与int
值进行比较,int
值将隐式转换为unsigned
类型。当您在比较中混合使用
signed
和unsigned
类型时,某些编译器会发出警告。在这种情况下,您可以将有符号值显式转换为适当的无符号类型以抑制警告。It is okay to compare a
size_t
value with anint
value, theint
value will be implicitly converted tounsigned
type.Some compilers will issue a warning when you mix
signed
andunsigned
types in comparisons. In that case you can explicitly convert thesigned
value to an appropriateunsigned
type to suppress the warning.