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.
来源:https://stackoverflow.com/questions/31347420/can-we-and-how-safe-is-to-signed-to-unsigned-trick-to-save-one-comparison-in