1

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 ?

Ondrej
  • 817
  • 1
  • 9
  • 16
  • 1
    In `C` (and by extension in `C++`) there is "As If Rule". So you overthink this. `constexpr` is not needed to optimize that. – Marek R May 07 '20 at 14:44
  • 1
    The standard doesn't specify how things work under the hood, so inlining is never guaranteed. – HolyBlackCat May 07 '20 at 14:48

2 Answers2

3

From http://eel.is/c++draft/dcl.constexpr#1.sentence-3

A function or static data member declared with the constexpr or consteval specifier is implicitly an inline function or variable.

anastaciu
  • 23,467
  • 7
  • 28
  • 53
1

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.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
  • 1
    I just went to the assembly of that code and you are right, the output assembler code was the same regardless I used `static constexpr`, `static`, `constexpr` or just pure `int`. Standard is telling that `static constexpr` is implicitly `inline` but it is on the compiler which optimization are performed. And in the end of the day these cases seems to be always inlined. – Ondrej May 07 '20 at 15:23
  • @Ondrej: `static constexpr` is only implicitly inline when it's a static *member* variable. – Nicol Bolas May 07 '20 at 15:53