The purpose of this blog is to help web developers to jump into systems programming. So you can ask any questions; there are no dummy questions. I want this blog to be a discussion space for every programmer on this journey.

As a JavaScript developer, you are probably familiar with the const keyword used to declare variables whose value cannot be changed.

However, diving into C++ programming, you may notice some differences in how const works compared to JavaScript. In this post, we’ll explore the nuances of const in C++ and how it differs from const in JavaScript.

By the end of this post, you’ll have the following:

  • A better understanding of how to use constness in C++
  • What is the difference between const & constexpr in C++
  • How it can help you write faster and more efficient code.

Constness in Javascript

In JavaScript, const is used to declare variables whose value cannot be re-assigned. Once a variable is declared with const, its value cannot be changed. For example:

const myVariable = 42;
myVariable = 43; // error - cannot re-assign const variable

Note that while the variable value cannot be re-assigned, the value of a const object or array can still be modified. For example:

const myObject = { x: 42 };
myObject.x = 43; // ok - can modify object property
const myArray = [1, 2, 3];
myArray.push(4); // ok - can modify array contents

However, you cannot re-assign a const object or array to a new value:

const myObject = { x: 42 };
myObject = { x: 43 }; // error - cannot re-assign const object 
const myArray = [1, 2, 3];
myArray = [4, 5, 6]; // error - cannot re-assign const array

Overall, in JavaScript, const only guarantees that the binding between the variable name and the value it points to is immutable, but the value itself can be mutable. It can help prevent accidental changes to variable values and improve code safety.

Note that you can use several other way to make an object fully immutable, for example with Object.freeze or with Proxy.

Constness in C++

These keywords are used to specify immutability, but they have different meanings and use cases. const

const is used to declare variables whose value cannot be changed. Once a variable is declared as const, its value cannot be modified during the execution of the program. They are not required to be initialized with a constant expression.

// Declare a const variable
const int my_variable = 42;

// Attempt to re-assign the const variable
my_variable = 43; // Error - cannot modify const variable

// Declare a const object
const std::unordered_map<std::string, int> my_map = x;

// Attempt to modify the const object
my_map["y"] = 43; // Error - cannot modify const object

// Initialize const variable with non-constant expression
const int array_size = std::rand();

“Hey but what is a constant expression?”

A constant expression is an expression whose value is known at compile time and does not change during the execution of the program.

In C++, several types of expressions can be constant expressions, including:

  • Literals, such as integer literals and string literals
  • Variables declared as constexpr
  • Functions declared as constexpr
  • Arithmetic operations on constants, such as addition, subtraction, multiplication, and division
  • Conditional expressions (if statements and ternary operators) where the condition and both possible results are constant expressions

I think that it’s the moment to introduce constexpr!

constexpr

constexpr is used to declare variables, functions, and expressions that can be evaluated at compile time. A constexpr variable must be initialized with a constant expression and must be of a type eligible for use in a constant expression. For example, the following code declares a constexpr variable my_variable and initializes it with a constant expression:

constexpr int my_variable = 42;

In this case, my_variable is a constexpr variable of type int that has a value of 42. Since my_variable is a constant expression, it can be used to define the size of an array, like this:

int myArray[myVariable];

In addition to defining the size of an array, constexpr variables help determine values that can be computed at compile time and used in constant expressions. For example, the following code defines a constexpr function square that computes the square of an integer:

constexpr int square(int x) {
  return x * x;
}

This function can be called with a constant expression argument, and the result can be used in a constant expression. For example:

constexpr int my_variable = square(6); // myVariable = 36
int my_array[my_variable]; // OK - use constexpr variable to define array size

Why constexpr is faster than const?

constexpr variables can be used to specify values that can be computed at compile time. This means that the value of a constexpr variable is known before the program is executed and can be substituted directly into the code, leading to faster and more efficient code.

In contrast, const variables can be initialized with any value, including those that cannot be computed at compile time (like the std::rand() we mentioned above). When a const variable is initialized with a non-constant value, such as the value of another variable, the compiler must evaluate the value of that variable at runtime. This can result in additional overhead and slower performance.

Summary

In summary, use const variables when you want to declare a variable whose value cannot be changed. Use constexpr variables when you want to declare a variable whose value can be computed at compile time and used in constant expressions.

Featureconst variableconstexpr variable
Variable immutabilityVariable value cannot be changedVariable value cannot be changed
Variable initializationCan be initialized with any valueMust be initialized with a constant expression
Variable typeAny typeMust be of a type eligible for use in a constant expression
Evaluation timeRuntimeCompile-time
Use caseDeclare variables that should not change at runtimeDeclare variables whose values can be computed at compile time and used in constant expressions

When using a variable to specify the size of an array, both const and constexpr variables can be used interchangeably.