constexpr (constant expression)

Tells compiler that function or variable should be evaluated at compile time, allowing the compiler to perform computations during compilation rather than at runtime.
Also function body should not contain any code which need runtime calculations.
- Below code is not candidate of constexpr

constexpr int dynamicSquare(int x) {
    return x * time(nullptr);  // Invalid, time() is not constexpr
}                
            

Use cases of constexpr

Compile-Time Evaluation

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

int main() {
    constexpr int result = square(5);  // Computed at compile time
    // ...
}    
                
Array initialization

constexpr int size = 5;
int array[size] = {1, 2, 3, 4, 5};  // Compile-time initialization                       
                
Constant Expressions

//constexpr can be used to define constants, 
allowing them to be used in contexts where only constant expressions are allowed
constexpr double pi = 3.14159;                     
                
Template Metaprogramming

//generate code at compile time
template <int N>
    constexpr int factorial() {
        return N == 0 ? 1 : N * factorial();
    }
    
    int main() {
        constexpr int result = factorial<5>();  // Computed at compile time
        // ...
    }                                            
                
Performance Optimization

//improved performance by allowing the compiler to optimize and eliminate runtime computations
constexpr int computeValue() {
    // Some computation
    return result;
}

int main() {
    constexpr int value = computeValue();  // Computed at compile time
    // ...
}                                                             
                

constexpr vs macro

Macros in C++ are a form of text substitution done by the preprocessor
Macros are not subject to the same rules and restrictions as constexpr
Macros replace code at the preprocessing stage, and they don't have a clear understanding of the C++ language constructs
Macros are not type safety
They are not guaranteed to be evaluated at compile time

#define SQUARE(x) ((x) * (x))
int main() {
    int result = SQUARE(5 + 1);  // Expanded to (5 + 1 * 5 + 1), unexpected behavior
    // ...
}                
            

constexpr variables

1. must be immediately initialized
2. Must have constant destruction. if of class type(class must have constexpr destructor).

constexpr function

1. Should not be virtual
2. Must not be a coroutine
3. function body must not contain: goto block

constexpr contructor

1. whose function body is not = delete;