投放ssize_t或size_t [英] Cast ssize_t or size_t

查看:136
本文介绍了投放ssize_t或size_t的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我在项目中使用的源文件中, ssize_t size_t 变量之间有一个比较:

  ssize_t sst; 
size_t st;

if(sst == st){...}

I想要摆脱警告:

 警告:有符号和无符号整数表达式之间的比较



但我不知道,应该将哪个变量投给另一个?

  if((size_t)sst == st){...} 


$ b b

  if(sst ==(ssize_t)st){...} 

什么是更安全,更好,更清洁?感谢

解决方案

这个问题没有正确的答案。有几种可能的答案,取决于您对这些变量可能采用的值的先验。




  • 如果您知道 sst 是非负数,那么您可以安全地将 sst c $ c> size_t ,因为这不会更改值(顺便说一句,如果你没有任何转换会发生什么)。


  • 如果 sst 可能为负值,但您知道 st 永远不会大于 SSIZE_MAX ,那么您可以安全地将 st 转换为 ssize_t


  • 如果 sst 可能为负值, st 可能大于 SSIZE_MAX ,则两个强制转换都不正确;任何一个可以更改值,导致不正确的比较。相反,您将执行以下 if(sst> = 0&&(size_t)sst == st)




如果您不是绝对确定,前两种情况之一适用,请选择第三个选项,因为它是正确的


In source files which I am using in my project, there is a comparison between ssize_t and size_t variables:

ssize_t sst;
size_t st;

if(sst == st){...}

I would like to get rid of the warning:

warning: comparison between signed and unsigned integer expressions

But I am not sure, which variable should I cast to the other?

if((size_t)sst == st){...}

or

if(sst == (ssize_t)st){...}

What is safer, better, cleaner? Thanks

解决方案

There is no one right answer to this question. There are several possible answers, depending on what you know a priori about the values that those variables may take on.

  • If you know that sst is non-negative, then you can safely cast sst to size_t, as this will not change the value (incidentally, this is what happens if you have no cast at all).

  • If sst might be negative but you know that st will never be larger than SSIZE_MAX, then you can safely cast st to ssize_t, as this will not change the value.

  • If sst might be negative, and st might be larger than SSIZE_MAX, then neither cast is correct; either one could change the value, resulting in an incorrect comparison. Instead, you would do the following if (sst >= 0 && (size_t)sst == st).

If you’re not absolutely certain that one of the first two situations applies, choose the third option as it is correct in all cases.

这篇关于投放ssize_t或size_t的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆