Const Evaluation
Const Variables
Variables declared const are evaluated at compile time:
const int MAX = 100;const float PI = 3.14159;const int DOUBLED = MAX * 2; // 200, computed at compile timeConst Functions
A trailing const qualifier marks a function as evaluable at compile time:
int Square(int x) const { return x * x; }int Add(int a, int b) const a + b; // expression body
const int result = Square(5); // 25, evaluated at compile timeExplicit Const Evaluation
Use const(expr) to force compile-time evaluation of any const-eligible expression:
int Factorial(int n) const{ if (n <= 1) { return 1; } return n * Factorial(n - 1);}
int x = const(Factorial(10)); // computed at compile timeWhat’s Allowed in Const Context
- Integer and float arithmetic, bitwise operations
- Comparisons and logical operators
- Control flow:
if/else,while,for,return - Recursive function calls (with depth limits)
- Local variable declarations and assignments
- Calls to other
constfunctions
What’s Not Allowed
- Heap allocation (
new,new*) - GC operations
- Console/I/O or system calls
- Pointer operations
- Calling non-const functions
Recursion
Const functions support recursion with a compile-time depth limit:
int Fib(int n) const{ if (n <= 1) { return n; } return Fib(n - 1) + Fib(n - 2);}
const int fib10 = Fib(10); // 55