Dynamic initialisation of a variable refers to variables that are initialised at runtime rather than at compile time. Consider the following example:
// return the sum of all numbers in the range [0:n]
const unsigned f (const unsigned n) { return n<=1?n:n+f(n-1); } // recursive!
int main (void) {
unsigned x {f (42)}; // dynamic initialisation
// ...
}
Here, x has to be dynamically initialised (at runtime) because the return value of f () cannot be determined at compile time.
The function f() has a linear time complexity (O(n) in big-O notation) however we can improve the execution time by removing all the recursions and reducing the function to a much simpler constant-time calculation:
// return the sum of all numbers in the range [0:n]
const unsigned f (const unsigned n) { return (n+1)*n/2; }
While this will greatly reduce the runtime cost, we still incur dynamic initialisation, albeit in constant time (O(1) as opposed to O(n)). Ideally we want to eliminate dynamic initialisations wherever possible.
Note that in the original call, we passed the constant value 42. Constant expressions such as this are extremely useful because they allow us to perform compile-time computation and thus avoid (some) dynamic initialisation. We can take advantage of this by declaring the function constexpr rather than just const:
// return the sum of all numbers in the range [0:num]
constexpr unsigned f (const unsigned n) { return (n+1)*n/2; }
int main (void) {
unsigned x {f (42)}; // static initialisation
// ...
}
Through compile-time computation, the example is now functionally equivalent to:
int main (void) {
unsigned x {903}; // static initialisation
// ... }
In other Words, the function call is eliminated completely so we incur no runtime cost at all. The value 903 is the return value of f (42). Just as importantly, if we subsequently called the function with a variable expression, the compiler will generate a function call which will be invoked at runtime. Thus we get the best of both worlds: compile-time computation when possible and constant-time dynamic initialisation if (and only if) it is needed.
Copyright © 2026 eLLeNow.com All Rights Reserved.