example_c99.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/*
     In the code below, the square(5) function might not be evaluated 
     at compile time, even though value is declared as const. This can 
     lead to potential inefficiencies and unintended runtime behavior, 
     such as errors when using value in contexts where a compile-time 
     constant is required (e.g., as an array size).
 */

#include <iostream>

int square(int x) {
    return x * x;
}

const int value = square(5);  // Not guaranteed to be a compile-time constant

int main() {
    // Size of the array must be known at compile time. 
    // Code compiles and runs on mac. No guarantees. 
    int arr[value];  // Might cause a runtime error if `value` is not a constant
    std::cout << "Value: " << value << std::endl;
    return 0;
}
Back to constexpr