constexpr in c++ 11 is a new added feature. constexpr is short name of  constant expression. in c++ 11 it is possible to evaluate the value of the function or variable at compile time by using ‘constexpr’ specifier. Let us take a very simple example to understand the use of constexpr.

Let us try to compile to compile below code.

This error comes because compiler is unable to compute the return value of function foo at compile time. But we can declare function foo constexpr so that compiler can evaluate it at compile time. see below code.

A function declared with constexpr is also known as constant expression function. In the above example foo is a constant expression function.

Limitation of constexpr

  • A function with multiple return statement is not allowed to be constant expression function. So following code will not complie as foo has multiple return statement.

  • Function must have non-void return type. The below code will not compile because foo has non-void return type.

  • The function body cannot declare variables or define new types.

constexpr constructor

A constexpr constructor allows the compiler to initialize the object at compile-time if the constructor’s arguments are all constant expressions.


Related Contents to follow