Say I have a function like this:
inline int shift( int what, int bitCount )
{
return what >> bitCount;
}
It will be called from different sites each time bitCount
will be non-negative and within the number of bits in int
. I'm particularly concerned about call with bitCount
equal to zero - will it work correctly then?
Also is there a chance that a compiler seeing the whole code of the function when compiling its call site will reduce calls with bitCount
equal to zero to a no-op?
According to K&R "The result is undefined if the right operand is negative, or greater than or equal to the number of bits in the left expression's type." (A.7.8) Therefore >> 0
is the identity right shift and perfectly legal.