Search code examples
c++optimizationstaticinlineconstexpr

Are static constexpr variables inlined in C++?


Lets have following code in C++14:

using namespace std;

void foo(int a)
{
    cout << a;
}

int main()
{
    //version1
    foo(13);

    //version2
    static constexpr int tmp = 13;
    foo(tmp);

    return 0;
 }

Will the compiler automatically optimize version2 to version1 so that static constexpr variable will be inlined (something like defines are handled during processor in C)? If so, what are the rules for this? Will it be still inlined if it would be only constexpr or static const ?


Solution

  • Compilers are given wide latitude under the "as if" rule to optimize as they see fit. Given the fairly trivial nature of the code you posted, a compiler is just as capable of optimizing "version 2" even if you removed static constexpr from the definition. The compiler can see that you don't change the value of the variable between its initialization and its use, and it can see that the use is a compile-time value, so it can call that function with the initialization value. And even optimize the function itself away if it can see the definition.

    Whether any particular compiler will or won't optimize away some code depends on compiler settings and the particular details of the code (specifically, code that intervenes between the value's creation and its use). There are no "rules" for this.