Ch7.1: constexpr Functions
Overview
A constexpr function is a function that may be evaluated at
compile time. This chapter focuses only on how to define such a function
correctly and what rules apply to its definition.
A constexpr function is also implicitly inline.
This allows you to place its definition in a header without causing
duplicate symbol errors across translation units.
Defining a constexpr function
To define a constexpr function, place the keyword
constexpr before the return type:
constexpr int add(int a, int b)
{
return a + b;
}
A constexpr function must follow the rules of constant
expressions. In practice, this means:
- the function must return a value
- it cannot perform I/O
- it cannot modify global variables
Because constexpr implies inline, defining such
functions in header files is safe and avoids multiple-definition errors.
Example
constexpr int square(int x)
{
return x * x;
}
This function is valid in constant expressions and safe to place in a header file.
Key takeaways
constexprdefines a function that may run at compile time.constexprfunctions are implicitlyinline.- They must follow the rules of constant expressions.
- They are safe to define in header files.