×

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

Differences Between C Structures and C++ Structures

The below table clearly describes the differences between C and C++ programming languages Structures concepts where the core principle concepts like static members, data handling, pointers, access modifiers, the importance...

3 minutes read.

C++ Socket Programming

In this world, computer networking has become very important for sharing of data. Every good programmer has some knowledge about computer networking. Socket programming is one of the critical topics...

6 minutes read.

C++ Namespaces

An Overview In each scope, a name can only represent one entity. As a result, there cannot be two independent variables with the similar names in the same scope, as this may cause...

10 minutes read.

INT_MAX and INT_MIN in C/C++

In competitive programming, assigning a variable that maximum or minimum value a data type can carry is frequently necessary. Still, it might be challenging to recall such a significant, exact...

3 minutes read.

Stringstream in C++ and its applications

In this tutorial, we will explore what the stringstream in C++ is. We will also learn its application. What is stringstream? With the aid of a stringstream, user can read from a...

2 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.

Functions in C++ with Types and Examples

A function is a collection of statements that work together to complete a certain goal. It could consist of statements that execute repetitive operations or statements that conduct specialized jobs...

10 minutes read.

C++ History

C++ is a middle-level programming language developed in 1980s by Bjarne Stroustrup at Bel Labs. C ++ development initially started in 1979, four years before its launch. It is started with...

1 minute read.

C++ Features

C++ is a general-purpose programming language that evolved from the C language to include an object-oriented paradigm. It is a compiled and imperative language. Object-Oriented Programming Object-oriented programming language concepts: ClassObjectsEncapsulationPolymorphismInheritanceAbstraction Class: A Class...

4 minutes read.

C++ References

C++ References An alias is a reference variable that is another name for a variable already in existence. If a relation is initialized with a variable, it is possible to use...

3 minutes read.

Counting Frequencies of Array Elements in C++

We have an array of integer items with duplicate values, and our objective is to compute the frequencies of the different elements in the array. Methods: Methods that can be used to...

3 minutes read.

C++ Signal Handling

Signals are interruptions sent by the operating system to a process to cause it to cease doing its current job and focus on the task for which the interrupt was...

4 minutes read.

C++ Tricks for Competitive Programming

If you are interested in Computer science or Information technology, you must have heard about competitive programming. Competitive programming is a way to improve your problem-solving skills. There are various...

7 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.

C++ Program to find the element that occurs once

Write a program to find the element in the array that occurs once. Given that all the numbers in the array are present two times and the array is sorted,...

7 minutes read.

Diamond Pattern Using Do-While loop in C++

What is Do-While Loop? An iterative loop that checks the condition at the end.The Do-While loop can be used whenever a test condition is specific, as the control enters the loop...

5 minutes read.

C++ Friend Functions

In C++, friends are special functions that are not a part of a class yet have access to its private and protected members. The friend keyword is used to declare...

4 minutes read.

How is multiset implemented in C++

Similar to sets, multisets are an associative container type where several items may share the same values. Associative containers implement instantly searchable sorted data structures with O(log n) complexity. In a multiset,...

5 minutes read.

How to initialize a dynamic array in C++

Regular arrays or static arrays have a predetermined size or fixed size. Change in the size of regular arrays is not possible. The memory size for static arrays determines at compile...

4 minutes read.

OOPs Concepts in C++

C++ Object-Oriented Programming Concepts C++ uses the concept of object-oriented programming. Object Oriented Programming has some prominent features: Object Class Data abstraction Encapsulation Polymorphism Inheritance Message passing Object An object is the basic unit...

2 minutes read.