Table of Contents
The constexpr keyword declares values that can be evaluated during compilation. A compile-time constant can be used wherever a constant expression is required, such as array sizes, template arguments, and switch case labels.
This example demonstrates how to declare a compile-time constant using constexpr.
Source Code #
#include <iostream>
int main()
{
constexpr int days_in_week = 7;
std::cout << "Days in a week: " << days_in_week << '\n';
return 0;
}
Output #
Days in a week: 7
Explanation #
constexpr int days_in_week = 7;declares a compile-time constant nameddays_in_week.- The value of a
constexprobject must be known during compilation. - A
constexprobject is implicitlyconstand cannot be modified after initialization. - Unlike a regular
constobject, aconstexprobject is guaranteed to be a constant expression when initialized with a compile-time value. std::cout << "Days in a week: " << days_in_week << '\n';prints the value of the compile-time constant.return 0;terminates the program successfully.