C++ · Module 2 · Lesson 41 min read

Constants: const & constexpr

const — read-only after initialization

ini
const double VAT = 0.13;
VAT = 0.15;   // ERROR: assignment of read-only variable
  • Must be initialized when declared
  • The value can come from runtime: const int age = read_age();

constexpr — known at compile time

ini
constexpr int MONTHS = 12;
constexpr double PI = 3.14159265358979;
  • The value must be computable by the compiler
  • Can be used where a compile-time constant is required: array sizes, template arguments, static_assert
  • ✅ Prefer constexpr for true constants

constexpr functions

arduino
constexpr int square(int x) { return x * x; }
constexpr int area = square(12);   // computed while compiling!

They can also be called at runtime with runtime values.

consteval and constinit (C++20)

  • consteval function: must run at compile time
  • constinit variable: must be initialized at compile time (avoids startup-order bugs with globals)

Why not #define?

arduino
#define MAX 100          // C style: plain text replacement
constexpr int MAX = 100; // C++ style ✅

constexpr has a type, respects scope, shows up in the debugger, and can't be accidentally redefined.

const everywhere

Make variables const unless they need to change. It documents intent and prevents bugs:

ini
const auto total = price * qty;

static_assert

Checks a condition at compile time:

arduino
static_assert(sizeof(int) == 4, "this code assumes 32-bit int");

Example

C++
#include <iostream>

constexpr int MONTHS = 12;
constexpr double VAT_RATE = 0.13;

constexpr int square(int x) { return x * x; }
consteval int kilobytes(int kb) { return kb * 1024; }     // C++20: compile time only

int main() {
    constexpr int board_cells = square(3);                 // computed by the compiler
    constexpr int max_upload = kilobytes(500);
    static_assert(board_cells == 9, "a tic-tac-toe board has 9 cells");

    int monthly_rent = 15000;
    const int yearly_rent = monthly_rent * MONTHS;          // const, but computed at runtime
    // yearly_rent = 0;                                     // error: read-only variable

    int user_input = 7;
    int runtime_square = square(user_input);                // constexpr function used at runtime

    double bill = 1500;
    std::cout << "Board cells: " << board_cells << '\n';
    std::cout << "Max upload bytes: " << max_upload << '\n';
    std::cout << "Yearly rent: Rs. " << yearly_rent << '\n';
    std::cout << "Square of 7: " << runtime_square << '\n';
    std::cout << "Bill with VAT: Rs. " << bill * (1 + VAT_RATE) << '\n';

    int scores[MONTHS] = {};                                // constexpr used as an array size
    std::cout << "Array holds " << sizeof(scores) / sizeof(scores[0]) << " months\n";
    return 0;
}

/* Output:
Board cells: 9
Max upload bytes: 512000
Yearly rent: Rs. 180000
Square of 7: 49
Bill with VAT: Rs. 1695
Array holds 12 months
*/