Constants in C++

Vishal Rashmika published on
2 min, 354 words

Categories: Cpp

1. Const

const is used to create immutable variables or functions. By making a function or variable a constant, we lose the ability to modify the content in runtime.

#include <iostream>

int main(){
	// immutable variable: the value of the variable cannot be changed to some other value
	const int pi = 3.141;

	return 0;
}

2. Constexpr (Constant Expressions)

The constexpr keyword is used to declare variables, functions, and constructors that can be evaluated at compile time. This allows for increased performance by executing calculations during compilation rather than runtime. constexpr provides a powerful optimization technique for creating efficient and reliable code in C++.

  • The result is hardcoded to the machine before runtime (hardcoded in compile time).
#include <iostream>

constexpr double pi = 3.141; // this variable will be available before runtime. will be hardcoded to the machine code

constexpr double area(const double radius){  
	/* 
	- this function will be hardcoded to the machine code 
	- this function doesn't need to be looked up everytime that it is called
	*/
	return pi * (radius * radius);
}

int main(){
    int area = area(2.5);
    std::cout << "Area of the Circle : " << area << std::endl;
	return 0;
}

3. Consteval

The "consteval" keyword is used to specify that a function must be evaluated at compile time. It ensures that the function is constexpr and will be computed at compile time whenever possible, providing performance benefits by avoiding runtime computations.

  • Result from a consteval function should be stored in an contexpr variable.
#include <iostream>

consteval int add(const int a, const int b){
	return a + b;
}

int main(){
	contexpr int answer = add(2,2);
    std::cout << "Answer : " << answer << std::endl;
	return 0;
}

4. Constinit

The "constinit" keyword is used to specify that a variable must be initialized at compile time with a constant expression. It ensures that the variable is initialized only once before any dynamic initialization occurs, helping to avoid order-of-initialization issues and promoting more predictable program behavior.

#include <iostream>

int sub(const int a, const int b){
	return a - b;
}

int main(){
	constinit int x = 10 // correct
	constinit int y = sub(10,5) // ERROR: the declaration value should be initialized at compile time.
}