Quick Q: Does constexpr guarantee compile-time evaluation? -- StackOverflow

Quick A: constexpr guarantees compile-time evaluation is possible if operating on a compile-time value, and that compile-time evaluation will happen if a compile-time result is needed.

From SO, the originally worded question:

Can C++ constexpr function actually accept non-constant expression as argument?

I have defined a constexpr function as following:

constexpr int foo(int i)
{
    return i*2;
}

And this is what in the main function:

int main()
{
    int i=2;
    cout<<foo(i)<<endl;
    int arr[foo(i)];
    for(int j=0;j<foo(i);j++)
        arr[j]=j;
    for(int j=0;j<foo(i);j++)
        cout<<arr[j]<<" ";
    cout<<endl;
    return 0;
}

The program was compiled under OS X 10.8 with command clang++. I was surprised that the compiler did not produce any error message about foo(i) not being a constant expression, and the compiled program actually worked fine. Why?

Add a Comment

Comments are closed.

Comments (1)

0 0

AndrewDover said on Jan 1, 2014 07:29 AM:

"We allow a constexpr function to be called with non-constant-expression arguments in contexts that do not require constant expressions, so that we don’t have to define essentially the same function twice: once for constant expressions and once for variables."

Page 9, bjarne stroustrup, a tour of c++