How to make the C++ compiler to use the unsigned to signed trick for optimization of comparison [duplicate]

社会主义新天地 提交于 2019-12-12 02:07:41

问题


So from what I know the following two functions' behavior should be exactly the same. However, if I implement using the first one, the compiler seems can't realize it's equivalent to the second. Is there anyway to hint the compiler to use the second ?

In another words, I hate to do the static_cast things... Anyway to avoid it?

// In my real use case, range will never be negative....
// All I want is to return (diff > range || diff < 0) assuming range >=0
bool IsOutofRange1(int diff, int range) {
  if ((range >= 0) && (diff > range || diff < 0)) return true;
  if (range < 0 && diff > range && diff < 0) return true;
  return false;
}

bool IsOutofRange2(int diff, int range) {
  if (static_cast<unsigned>(diff) > static_cast<unsigned>(range)) return true;
  return false;
}

回答1:


If your range in never negative, why do you use a signed type for it (yeah, I know you hate casting) ? How about overloading:

bool IsOutofRange(int diff, int range)
{
    ....
}

bool IsOutofRange(int diff, unsigned range)
{
    if (static_cast<unsigned>(diff) > range) return true;
    return false;
}

Of course to force compiler to use the second version you would (oh my God...):

IsOutofRange(diff,static_cast<unsigned>(range));

I hope that helps, and I am deeply sorry about the static_cast'ing.



来源:https://stackoverflow.com/questions/31352357/how-to-make-the-c-compiler-to-use-the-unsigned-to-signed-trick-for-optimizatio

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