1

I have following c++ code:

inline int choose(int i){
    static constexpr int arr[]={1,3,3,2,4,1,4}; 
    return arr[i];
}
void f(int);
int main(){
    for(int i=0;i<5;i++){
    f(choose(i));
    }
}

When I compile this with g++ 8.2 with option -O3, it produces well-optimized asm code. However, when I change the second line from static constexpr to constexpr, which should be semantically the same, it no longer optimizes array access, and produces somewhat inefficient asm code.

Does anyone have any idea why this happens?

eivour
  • 1,678
  • 12
  • 20
  • My guess, when the array is static the compiler knows where it will be whenever the function is called so it can unroll the loop and optimize away the function call and array access. When it is not static to location of the array can change so it can't/wont provide the optimization. – NathanOliver Nov 26 '18 at 13:48
  • @NathanOliver But when we write `constexpr` variable we don't expect it to be "real variable" (hence have memory address in stack or anywhere), so the compiler should be able to put it wherever it likes... – eivour Nov 26 '18 at 13:57
  • `constexpr` is there mostly to express [*intent*](https://stackoverflow.com/a/28821610/485343), so that the compiler can stop you when you try something that can't be done compile-time. It's more for the programmer than the compiler, which can (should) already see what can and cannot be optimized. As to the question - would "it's an improvement opportunity in GCC" be a sufficient answer? – rustyx Nov 26 '18 at 14:07

0 Answers0