Understanding constexpr specifier in C++

Let’s discuss constexpr specifier in C++. We use them to evaluate the value of the functions and variables at compile-time, and hence we save time at run time. The expression that the compiler evaluates, we can use it in other constant expressions. 

A constexpr variable should be literal, the initialization should be immediate and must be a constant expression, and should have constant destruction.

A constexpr function should have literal parameters and return types. The function body should only contain null statements, declarations, typedef, or directives. There should only be one return statement. There shouldn’t be goto, a try block, or variable declaration statements in the function body.  All the function and function template declaration must also contain the specifier.

Let’s understand through a code:

constexpr int sum(int x, int y) 

{ 

    return (x * y); 

} 

  
int main() 

{ 
    const int x = sum(100, 10); 

    cout << x; 

    return 0; 

}

Output:

110

Here x is defined as a constant as it stores the value at compile time and acts as a constant at run time.

Leave a Reply

Your email address will not be published. Required fields are marked *