Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

constexpr - What does "Evaluate value at compile time" mean exactly?

Tags:

c++

#include <array>

int value1(int param) {
    return param * 2;
}

constexpr int value2(int param) {
    return param * 2;
}

int main() {
    const int i = 10;

    std::array<int, value1(i)> starr1 = {}; // 1
    std::array<int, value2(i)> starr2 = {}; // 2

    return 0;
}

2 is okay, but 1 gives a compile error because std::array has to make static size array. value2() returns compile-time constant value because of constexpr keyword.

So, how does the compiler infer that value2(i) is compile-time constant? Does it call the function value2() while compiling?

const int value1(int param) {
    return param * 2;
}

int main() {
    const int i = 10;
    std::array<int, value1(i)> starr1 = {}; // 3

    return 0;
}

>>> error: call to non-constexpr function ‘const int value1(int)’

Also, 3 still tgives a compile error. Is value1(i) not compile-time constant even though const keyword is applied to the function value1()?

like image 426
EnDelt64 Avatar asked Jan 31 '26 06:01

EnDelt64


1 Answers

So, how compiler infer value2(i) is compile-time constant?

It doesn't infer that. You state that explicitly when you annotate it with constexpr. It might infer that for functions not marked with constexpr, though. This still won't allow you to use their results in compile-time expressions, and is only used as an optimization strategy.

Does it call the function value2() while compiling?

In a sense, yes. It's probably closer to interpreting it directly, since I don't think any compiler actually compiles that function for the purposes of executing it during the build. What matters is that it's able to establish its result before the entire program is built and ran, and that it can use that result to e.g. determine the size of your array when generating the code.

Is value1(i) not compile constant even though const keyword is applied to the function value1()?

It's not. const only applies to the return type (and in this case, it's effectively useless), not the evaluation possibility in compile-time.

like image 144
Bartek Banachewicz Avatar answered Feb 01 '26 20:02

Bartek Banachewicz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!