• Home
  • 1.8 Compile-Time Constants (constexpr)

1.8 Compile-Time Constants (constexpr)

View Categories

1.8 Compile-Time Constants (constexpr)

< 1 min read

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 named days_in_week.
  • The value of a constexpr object must be known during compilation.
  • A constexpr object is implicitly const and cannot be modified after initialization.
  • Unlike a regular const object, a constexpr object 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.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *