Constants using constexpr Keyword
The constexpr keyword is similar to const keyword and is also used to declare constants in C++. But the major difference is that the constexpr constants are initialized at compiler time, which is why their value must be known at the compile time. On the other hand, const keyword constants can be initialized at runtime and compile time.
Syntax for constexpr
constexpr DATATYPE variable_name = value ;
We first use the constexpr keyword to make sure that our variable is a constant followed by the DataType of the constant variable then proceed with the name of the constant variable and finally give the appropriate value to the constant variable.
Example for constexpr Keyword
C++
// C++ program to illustrate the use of constexpr keyword #include <iostream> using namespace std; int main() { // defining constant int constexpr hoursIn_day = 24; // printing value cout << "Total hours in a day: " << hoursIn_day; } |
Total hours in a day: 24
The above snippet uses the const and constexpr keywords to define constant the number of hours in a day (hoursIn_day)
Constants in C++
In C++, constants are values that remain fixed throughout the execution of a program. In this article, we will discuss various ways to define and use constants in C++.
Contact Us