Better Programming

Advice for programmers.

Follow publication

Member-only story

C++ constexpr: What It Really Is?

Debby Nirwan
Better Programming
Published in
5 min readMar 8, 2022

Photo by Luca Bravo on Unsplash

Overview

The constexpr specifier was introduced in C++11, for beginners it is confusing because it is similar to the const qualifier.

constexpr stands for constant expression and is used to specify that a variable or function can be used in a constant expression, an expression that can be evaluated at compile time.

The key point of constexpr is that it can be executed at compile time. Your code may have been executed before you run it. That’s the main point.

We can use constexpr on variables, functions — including constructors, and if statements. We will see the details in the following sections.

Variables

I have written all the details about const qualifier in another article:

We use the const qualifier to express our intention to compilers and other programmers that we want the variable to be read-only and any attempt to modify it will result in a compilation error.

Now, constexpr is similar to const, in that it implies a const. It too, cannot be changed. The difference is, const can be evaluated at compile-time and run time, depending on how we initialize it.

In this example val is evaluated at compile-time. When we execute our code, val always equals 3. However, in the following example val is evaluated at run-time because it involves calling a function.

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Debby Nirwan
Debby Nirwan

Written by Debby Nirwan

Software Engineering Manager who loves reading, writing, and coding.

Responses (1)

Write a response

Great read, and to the point explanation! Thanks a ton Debby.