Will bit-shift by zero bits work correctly?

后端 未结 6 917
轮回少年
轮回少年 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条回答
  •  野性不改
    2021-02-04 03:30

    About the correctness of arg << 0 or arg >> 0, no problem, absolutely fine.

    About the eventual optimizations: This will not be reduced to a >nop< when called with a constant what=0 and/or bitcount=0, unless you declare it as inline and choose optimizations (and your compiler of choice understands what inline is).

    So, bottom line, optimize this code by conditionally calling the function only if the OR of arguments is non zero (about the fastest way I figure to test that both args are non-zero).

提交回复
热议问题