Will bit-shift by zero bits work correctly?

后端 未结 6 922
轮回少年
轮回少年 2021-02-04 03:15

Say I have a function like this:

inline int shift( int what, int bitCount )
{
    return what >> bitCount;
}

It will be called from diffe

6条回答
  •  梦毁少年i
    2021-02-04 03:24

    The compiler could only perform this optimisation do that if it knew at compile time that the bitCount value was zero. That would mean that the passed parameter would have to be a constant:

    const int N = 0;
    int x = shift( 123, N );
    

    C++ certainly allows such an optimisation to be performed, but I'm not aware of any compilers that do so. The alternative approach the compiler could take:

    int x = n == 0 ? 123 : shift( 123, n );
    

    would be a pessimisation in the majority of cases and I can't imagine compiler writer implementing such a thing.

    Edit: AA shift of zero bits is guaranteed to have no effect on the thing being shifted.

提交回复
热议问题