×

Constexpr in C++

Constexpr is a keyword in C++ that is used to declare variables or functions as compile-time constants. This means that the value of a constexpr variable or the return value of a constexpr function must be known at compile time and cannot be changed at runtime.

One of the main benefits of using constexpr is that it enables the compiler to optimize the code simultaneously. This can lead to improved performance and reduced memory usage at runtime.

To declare a variable as a constexpr, add the keyword constexpr before the type in the declaration. For example:

constexpr int x = 10;

In this case, x is a compile-time constant with the value 10. You can also initialize a constexpr variable with the result of an expression, as long as the expression can be evaluated at compile time:

constexpr int y = x * 2; // y is equal to 20

You can also declare constexpr functions, which return a compile-time constant. Add the constexpr keyword before the return type in the function declaration to do this. For example:

constexpr int square(int x) {

  return x * x;

}

In this case, the square function returns the square of its input x. Because the return value of this function can be determined at compile time, it can be used in other constexpr declarations and expressions:

constexpr int y = square(10); // y is equal to 100

Note that constexpr functions can also have multiple statements and loops as long as the return value can be determined at compile time. However, not all functions can be declared as constexpr – for example, a function that generates a random number cannot be a constexpr function because the return value is not known at compile time.

Examples:

#include <iostream>


// Define a constexpr function to compute the square of a number
constexpr int square(int x) {
  return x * x;
}


int main() {
  // Compute the square of a number at compile time
  constexpr int a = square(5);


  // Print the result to the console
  std::cout << "The square of 5 is " << a << std::endl;


  return 0;
}

Output:

Constexpr in C++

Explanation:

In this code, the square function is declared as constexpr, which allows the call to square(5) in the main function to be computed at compile time. This can be useful for optimizing code and ensuring that certain values are known at compile time.

Here is another example of how constexpr can be used in C++:

#include <iostream>


// Define a constexpr function that returns the factorial of a number
constexpr int factorial(int n) {
  int result = 1;
  for (int i = 1; i <= n; ++i) {
    result *= i;
  }
  return result;
}


int main() {
  // Compute the factorial of a number at compile time
  constexpr int a = factorial(5);


  // Print the result to the console
  std::cout << "The factorial of 5 is " << a << std::endl;


  return 0;
}

Output:

Constexpr in C++

Explanation:

In this example, the factorial function is declared constexpr, allowing the main function's call to factorial(5) to be computed at compile time. This allows the value of the factorial to be known at compile time rather than having to be calculated at runtime.

Here is another example program that demonstrates the use of constexpr in C++:

#include <iostream>


// Define a constexpr function that calculates the sum of two numbers
constexpr int add(int a, int b)
{
    return a + b;
}


int main()
{
    // Use the constexpr function to calculate the sum of 5 and 7 at compile time
    constexpr int result = add(5, 7);
    
    // Print the result
    std::cout << "The sum of 5 and 7 is " << result << std::endl;
    
    return 0;
}

Output:

Constexpr in C++

Explanation:

This program defines a constexpr function called add that calculates the sum of two numbers. The constexpr keyword indicates that the function can be evaluated at compile time if the arguments passed are constant expressions. In the main function, we use the constexpr function to calculate the sum of 5 and 7 and print the result.

Since the arguments passed to the add function are constant expressions (the literal values 5 and 7), the function is evaluated at compile time, and the result is stored in the result variable. This means that the add function does not need to be executed at runtime, which can improve the program's performance.


Related Topics

Vector Size in C++

What are Vectors?  In the C++ programming language, vectors are run-time sequence containers representing arrays with variable sizes, which are contained within STL (Standard Template Library). They utilize contiguous storage spaces...

6 minutes read.

strcat() vs strncat() in C++

In this tutorial, we will explore about strcat() and strncat() in the most usable language C++. We will also look at the difference between them. strcat() C++ is a computer language with...

4 minutes read.

Sizeof() Operators in C++

sizeof() Operators in C++ The sizeof() operator in C++ defines the size of variables, constants, or data types. It is a unique operator that manipulates other operators and returns the size...

4 minutes read.

Initialization of Data Members

In this tutorial, we'll look at how to initialise static member variables in C++. Static members, such as functions or variables, can be added to C++ classes. After declaring the...

1 minute read.

Classes and Objects in C++

When it comes to object-oriented programming, objects are the basic building blocks. Memory is taken up by objects, which contain data and methods or functions that operate on it. On...

3 minutes read.

Name Mangling and extern in C++

Name Mangling and Function Overloading: Function overloading is a feature offered by C++. As long as each function accepts various parameters, we can use this to write many functions with the...

4 minutes read.

C++ Call by Value

In this article, we will discuss C++ Call by Value with their syntax, examples, use cases, advantages, and disadvantages. C++ Function A function is a set of statements that executes a task....

5 minutes read.

Copy elision in C++

The Copy Omission is another name for the Copy Elision. One of the several compiler optimization techniques is copy elision. It prevents items from being copied inadvertently. This Copy Elision approach...

3 minutes read.

C++ String Class and its Applications

The String class is available in C++. The character array is represented by the C string. The string class in C++ has a few different attributes. It contains several functions...

4 minutes read.

How to create a button in C++

A button is an option through which a user can control to click a provided input to an application. There are several buttons, each with different styles, to maintain the...

3 minutes read.

Two dimension array

C++ Two dimension (2D) Array Two dimension (2D) array is an array of arrays. It is represented in the form of row and column. The elements of 2D array are accessed through the...

2 minutes read.

Single level Inheritance

Inheritance is a fundamental element of C++’s Object-Oriented Programming (OOP). It allows a class (called the derived class) to inherit characteristics and attributes from another class (called the base class)....

5 minutes read.

Pthreads or POSIX Threads in C++

The thread API for C/C++ is implemented by pthreads or POSIX threads. It enables the multithreading system, which enables parallel and distributed processing, and the creation of new concurrent process...

3 minutes read.

Maps in C++

Maps: Maps in C++ are the containers associated with key and mapped values. By keys and mapped values, we mean that the maps are used to store elements formed by the...

4 minutes read.

How to declare a 2D array dynamically in C++

In this article, we will learn how to declare the dynamic array in C++. We also learn the initialization of a 2D array using a pointer in C++. Here, we...

3 minutes read.

How to implement map in C++

Part of the C++ STL is maps (Standard Template Library). Maps are associative containers that hold sorted key-value pairs, where each key is distinct and may only be added or...

4 minutes read.

Converting string into integer in C++

When programming in C++, we'll frequently need to change one data type to another. When we use C++ to create apps, we must transform data from one type to another. When...

7 minutes read.

C++ cin and cout

In this article, we will discuss the C++ cin and cout with their library and examples. C++ Standard Input/Output: User-program communication is made possible by C++’s usage of input and output (I/O)...

5 minutes read.

Single Handling in C++

Introduction: Single handling in C++ refers to a technique for processing multiple events or requests with a single function or handler rather than creating separate functions for each task. This allows...

5 minutes read.

C++ Break

In this article, we will discuss the C++ Break statement with its syntax, algorithm, pseudocode, and examples. The C++ break statement also terminates the currently active loop or switch statement immediately....

4 minutes read.