bhylu.com

Advertisements

C++ constexpr

Use constexpr and static_assert for a fixed packing rule while keeping runtime values possible.

How it works

A constexpr function can participate in constant evaluation when its inputs and operations permit it. It can also be called at runtime with ordinary values. static_assert requires a compile-time true condition and rejects a build that breaks an invariant. This is useful for small pure rules and fixed configuration, not a reason to move external input handling into complicated templates. A compile-time check still covers only the condition you wrote, so choose cases that express meaningful boundaries.

Run it locally

Use a C++20 compiler and matching standard library in a separate lab folder. The command uses c++; substitute g++, clang++ or zig c++ for your toolchain. C++ does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.

c++ -std=c++20 -Wall -Wextra -Wpedantic -Werror constexpr.cpp -o lesson

On Windows use -o lesson.exe and run .\lesson.exe in PowerShell. On Unix-like systems run ./lesson. Thread examples may need -pthread on your platform.

Download the complete C++ source. Run file labs in a private empty directory, away from existing reports.

Example

C++20 · constexpr.cpp

#include <iostream>

constexpr int full_crates(int count, int capacity) {
    return capacity > 0 && count >= 0 ? count / capacity : 0;
}

int main() {
    constexpr int crates = full_crates(17, 5);
    static_assert(crates == 3);
    static_assert(full_crates(0, 5) == 0);
    std::cout << "Full crates: " << crates << '\n';
}

Expected result

Full crates: 3

The constants allow the compiler to verify both assertions. The helper returns zero for an invalid domain under this deliberately simple policy; a production interface should distinguish invalid input from a legitimate empty result if the caller needs that information. consteval instead requires compile-time evaluation for every call, and is a separate C++20 choice.

Consult the WG21 C++ working group and the C++ Core Guidelines for language references and design guidance. Check the selected standard version and your implementation’s library support.