Ch7: Compile‑Time Programming
Overview
Compile‑time programming allows the compiler to evaluate expressions, functions, and objects before the program runs. This can improve safety, correctness, and performance by catching errors early and avoiding unnecessary runtime work.
In this chapter, you will learn the core tools of compile‑time programming in C++:
constexprfunctionsconstexprobjectsif constexprif constevalconstinitconsteval
These features let you write code that can run either at compile time or runtime depending on context, and in some cases must run at compile time.
Contents
What you should know before starting
This chapter assumes you already understand:
- basic functions (Chapter 6)
- variables and initialization
- the difference between compile time and runtime
No templates, classes, or advanced metaprogramming are required. All examples use simple, practical C++.
Why compile‑time programming matters
- Safety: errors are caught earlier
- Performance: work done at compile time is not repeated at runtime
- Correctness: invariants can be enforced before the program runs
- Clarity: intent is explicit when something must be known at compile time
Modern C++ encourages using compile‑time features when they make code clearer and safer, not for clever tricks.