Site icon Embarcadero RAD Studio, Delphi, & C++Builder Blogs

Learn How To Use constexpr In Modern C++ With C++Builder For Windows Development

constexpr modern c

In this tutorial, you will learn how to utilize constexpr variables and constexpr functions. The principal idea is the performance enhancement of applications by doing calculations at compile time rather than run time. The purpose is to allocate time in the compilation and save time and run time.

The constexpr keyword was introduced in C++11 and improved in C++14 and C++17. constexpr specifies that the value of an object or a function can be evaluated at compile-time and the expression can be used in other constant expressions. A compiler error is raised when any code tries to alter the value. Unlike const, constexpr can also be applied to functions and class constructors. constexpr symbolizes that the value or return value is constant and where possible is calculated at compile time.

The primary difference between const and constexpr variables is that the initialization of a const variable can be deferred until run time. A constexpr variable must be initialized at compile time. Moreover, all declarations of a constexpr variable or function must have the constexpr specifier.

[crayon-6767de08081c9528546466/]

With C++17, we can estimate conditional expressions at compile time. The compiler is then able to eliminate the false branch.

[crayon-6767de08081cf027477914/]

You can do more amazing things with if constexpr. Be sure to check out these workshops:

constexpr Functions

A constexpr function is one whose return value is computable at compile time when consuming code requires it. A constexpr function or constructor is implicitly inline.

[crayon-6767de08081d1166300671/]

Example

The following sample shows constexpr variables, functions and several use cases

[crayon-6767de08081d2941858042/]

Be sure to check out more modern C++ samples on this repository!

Next, find out how you can convert Int to String C++ in this article about Modern C++ Software.

Exit mobile version