C 中模数(数学函数)的等价物?
我有一段代码,其中显示一条警告:
我正在对有符号数字和无符号数字进行比较。
像 int <= CONSTANT/sizeof(expression) 之类的东西
纠正这个问题的最佳方法是什么?我相信取有符号数的模然后进行比较,对吧?我的意思是我在表达式上除以 sizeof 运算符后得到无符号数。所以另一种方法可能是让这个 rhs 签名
如果是的话,c 中有一个函数可以让我这样做吗?我进行了快速搜索,他们说 % 表示模数,这显然不是我要找的。
这是实际的警告
警告:有符号和无符号整数表达式之间的比较
,这是实际的代码行
函数A(......, int num, ....) {
assert( num <= MAX_SIZE/sizeof(int));//其中 MAX_SIZE 为 #define MAX_SIZE 1000
}
I have a piece of code where I see a warning saying
I am doing a comparison between signed and unsigned number .
Something like int <= CONSTANT/sizeof(expression)
What is the best way to correct this? I believe to take the modulus of signed number and then do the comparison, right? I mean I get the unsigned number after division by sizeof operator on an expression. So the other way could be to make this rhs signed
If so is there a function in c that would let me do this? I did a quick search and they say % for modulo which obviously is not what I am looking for.
This is the actual warning
warning: comparison between signed and unsigned integer expressions
and this is the actual line of code
functionA( ......, int num, .....) {
assert( num <= MAX_SIZE/sizeof(int));//where MAX_SIZE is #define
MAX_SIZE 1000}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您知道正确的操作数是 <=
INT_MAX
,则可以将其强制转换为int
。但是,如果您可以将对象
bla
的类型更改为size_t
(这是sizeof
生成的值的类型),那就更好了比铸造。If you know the right operand is <=
INT_MAX
, you can cast it toint
.But if you can change the type of object
bla
tosize_t
(which is the type of the value thatsizeof
yields) it would be even better than to cast.只需将一侧投射到另一侧即可。如果将其转换为无符号数,则必须确保有符号数不是负数 - 否则
-1
-1
-1
-1
-1
-1
100
将不会得到所需的结果,因为(unsigned)(-1) == UINT_MAX
-,或者如果将其转换为有符号,则无符号数不会溢出。在这些情况下,添加额外的条件来治疗它们。对于上述特殊情况,我将使用
if
num
可能为负数并且if
num
保证为非负数。Just cast one side to the other signedness. You have to make sure that the signed number is not negative if you cast that to unsigned - otherwise a comparison of
-1 < 100
will not have the desired outcome, since(unsigned)(-1) == UINT_MAX
-, or that the unsigned number doesn't overflow if you cast that to signed. In those cases, add an additional condition to treat them.For the above particular case, I would use
if
num
might be negative andif
num
is guaranteed to be nonnegative.正如我所看到的,您的
int num
允许采用任何负值和正值,最大为MAX_SIZE/sizeof(int)
。否则,您肯定会将num
声明为无符号整数...通过此附加条件扩展您的断言语句对您的情况有帮助吗?
As I see this, your
int num
is allowed to take any negative value and positive values up toMAX_SIZE/sizeof(int)
. Otherwise you would have declarednum
as an unsigned integer for sure...Would extending your assertion statement by this additional condition help in your case?