我们如何安全是可以到"签署"到"无符号"招保存在这个情况下,一个比较呢? [英] Can we and how safe is to "signed" to "unsigned" trick to save one comparison in this case?
问题描述
例如
布尔CheckWithinBoundary(INT X,INT B){
则返回(x&GT = 0)及&放大器; (X LT; = b)的;
}
布尔CheckWithinBoundary2(INT X,INT B){
返回的static_cast<&UINT32 GT;(x)的< =的static_cast<&UINT32 GT;(二);
}
CheckWithinBoundary2还能再救一个比较。
我的问题是:
-
,今天的编译器优化code。使用呢?或者,我该怎么做
编译器做这种优化的? -
有没有危险,用这一招?
这个问题的答案2,对了,还有,这两个是不一样的。看来你是默默的假设 B> = 0
,太。考虑如 X == 1
和 B == -1
,这将给假
对于第一种情况和真正
第二。
(我切换到C符号,这很容易给我,因为你似乎也有兴趣吧)
因此,我们必须在事实上
static_assert(INT_MAX< UINT_MAX);布尔CheckWithinBoundary(INT X,INT B){
返回(B个= 0)及&放大器; (X GT = 0)及&放大器; (X LT; = b)的;
}
布尔CheckWithinBoundary2(无符号X,无符号B){
返回(B个= 0)及&放大器; (X LT; = b)的;
}
如果汇编,是等价的在所有的架构,其中 INT_MAX< UINT_MAX
,然后隐式转换 INT - >无符号
做正确的事。
但要小心,你注意,我用无符号
,而不是 uint32_t的
,因为你必须要确保使用无符号类型有相同的宽度。我不知道是否有与64位架构 INT
,但你的方法会失败。
For example
bool CheckWithinBoundary(int x, int b) {
return (x>=0) && (x <= b);
}
bool CheckWithinBoundary2(int x, int b) {
return static_cast<uint32>(x) <= static_cast<uint32>(b);
}
CheckWithinBoundary2 can save one comparison.
My question is:
Can today's compiler optimize code using this? Or how can I make the compiler do this kind of optimization?
Is there any danger to use this trick?
The answer to 2 is, yes, there is, these two are not the same. It seems that you are silently assuming that b >= 0
, too. Consider e.g x == 1
and b == -1
, this would give false
for the first case and true
for the second.
(I switch to C notation, this is easier to me, and since you also seem to be interested in it)
So we have that in fact
static_assert(INT_MAX < UINT_MAX);
bool CheckWithinBoundary(int x, int b) {
return (b >=0) && (x>=0) && (x <= b);
}
bool CheckWithinBoundary2(unsigned x, unsigned b) {
return (b >=0) && (x <= b);
}
if it compiles, are equivalent on all architectures where INT_MAX < UINT_MAX
, and then the implicit conversion int --> unsigned
does the right thing.
But be careful, you note that I use unsigned
and not uint32_t
, because you have to be sure to use an unsigned type with the same width. I don't know if there are architectures with 64 bit int
, but there your method would fail.
这篇关于我们如何安全是可以到&QUOT;签署&QUOT;到&QUOT;无符号&QUOT;招保存在这个情况下,一个比较呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!