Search code examples
c++optimizationcompilationchess

Are const constant operations evaluated at run time?


I'm doing some chess programming in C++, as a result there are a lot of bitwise operations that I have to do with some large numbers. I was wondering, for perfomance sake if constant operations are done at runtime? Or if they're evaluated during compilation. e.g. Suppose I have to AND the following 2 constants:

const unsigned long long FILE_A = ~0x8080808080808080;
const unsigned long long FILE_B = ~0x4040404040404040;

In a function like this

unsigned long long join(){
    return (FILE_A & FILE_B);
}

Is the AND operation on FILE_A and FILE_B done at runtime? Or does the compiler do it?


Solution

  • In general: a C++ compiler is allowed to do any optimization as long as the result of the optimization is "as if" the code was executed literally.

    In the example you gave, doing the given calculation at compile-time is indistinguishable to doing it at run time; so modern C++ compilers will do exactly that. In fact, modern C++ compilers, if join() is defined in a header file (with an inline attribute) -- and if a moderate optimization level is selected -- will not only make the calculation at compile time, but completely optimize join() away, and inject the computed constant directly wherever join() gets used, making possible additional compile-time optimizations. That's because the result would be indistinguishable from the result if nothing was optimized away.