Can we and how safe is to “signed” to “unsigned” trick to save one comparison in this case?

白昼怎懂夜的黑 提交于 2019-12-02 04:49:45

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!