example_c11.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
/*
    C++11 introduced constexpr, which allows you to define functions 
    and variables that are guaranteed to be evaluated at compile time, 
    provided that all inputs are known at compile time. This makes code 
    more efficient and allows for safer and more predictable behavior.
 */

#include <iostream>

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

constexpr int value = square(5);  // Guaranteed to be a compile-time constant

int main() {
    int arr[value];  // Safe to use `value` as an array size
    std::cout << "Value: " << value << std::endl;
    return 0;
}
Back to constexpr