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?
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).
To make the function somewhat self documenting, you may want to change bitCount to unsigned to signify to callers that a negative value is not valid.
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.
It will work correctly on any widely used architecture (I can vouch for x86, PPC, ARM). The compiler will not be able to reduce it to a noop unless the function is inlined.
It is certain that at least one C++ compiler will recognize the situation (when the 0 is known at compile time) and make it a no-op:
Source
Compiler switches
Intel C++ 11.0 assembly
As you can see at ..B1.1, Intel compiles "return shift(42,0)" to "return 42."
Intel 11 also culls the shift for these two variations:
For the case when the shift value is unknowable at compile time ...
... the shift cannot be avoided ...
... but at least it's inlined so there's no call overhead.
Bonus assembly: volatile is expensive. The source ...
... instead of a no-op, compiles to ...
... so if you're working on a machine where values you push on the stack might not be the same when you pop them, well, this missed optimization is likely the least of your troubles.
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:
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:
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.