Does a c/c++ compiler optimize constant divisions by power-of-two value into shifts?

后端 未结 4 603
清歌不尽
清歌不尽 2020-11-30 05:49

Question says it all. Does anyone know if the following...

size_t div(size_t value) {
    const size_t x = 64;
    return value / x;
}

...i

4条回答
  •  无人及你
    2020-11-30 06:11

    Only when it can determine that the argument is positive. That's the case for your example, but ever since C99 specified round-towards-zero semantics for integer division, it has become harder to optimize division by powers of two into shifts, because they give different results for negative arguments.

    In reaction to Michael's comment below, here is one way the division r=x/p;of x by a known power of two p can indeed be translated by the compiler:

    if (x<0)
      x += p-1;
    r = x >> (log2 p);
    

    Since the OP was asking whether he should think about these things, one possible answer would be "only if you know the dividend's sign better than the compiler or know that it doesn't matter if the result is rounded towards 0 or -∞".

提交回复
热议问题