C++11 constexpr Keyword

In this chapter, you will learn about the new keyword - constexpr that can enable programmers to enable any associated expressions to be evaluated at compile time.

With the standardization of C++11, the keyword - 'constexpr' can be implemented for enabling which expressions needs to be evaluated at compile time.

Let's suppose:

Example:
constexpr int cube (int a)
{
    return a * a * a;
}

float gk[cube(3)]; // Valid since C++11: variable 'gk' has 27 elements

With the introduction of this keyword, many problems got fixed in C++98 when using numeric limits. Before the arrival of C++11, an expression such as std::numeric_limits<short>::max() can't be used as an integral constant, even though it was functionally equivalent to the macro INT_MAX. But now, with the newer advancement of C++11, this kind of expression is termed as 'constexpr' and so you can use it to state different arrays or in compile-time computations (which is generally called as meta-programming).


Courses
Subscribe Updates via Email

Join 49,000+ W3schools lovers and get all the latest tutorials, programs, algorithms in your inbox.