Dynamic initialization is that the initialization value is unknown at compile time. It was computed at runtime to initialize the variable.
Example
int factorial(int n) { if ( n < 0 ) return -1; //indicates input error else if ( n == 0 ) return 1; else return n * factorial(n-1); } int const a = 10 ; //static initialization //10 is known at compile time. Its 10! int const b = factorial(8); //dynamic initialization //factorial(8) isn't known at compile time, //rather it computed at runtime.
That is, static initialization usually includes a constant expression (which is known at compile time), while dynamic initialization includes a non-constant expression.
static int c;
Β§3.6.2 / 1 of the C ++ (2003) standard states:
Objects with a static storage duration (3.7.1) must be zero (8.5) before any other initialization occurs. Zero initialization and initialization with an expression constant are called collectively static initialization ; all other initialization dynamic initialization .
So there are two types of initializations:
- Static initialization: either zero initialization or constant expression initialization
- Any other initialization is dynamic initialization.
Also note that the same variable can be dynamically initialized after static initialization. For example, see this code:
int d = factorial(8); int main() { }
Since d is a global variable, it has static storage. This means that according to Β§3.6.2.1 it is initialized to 0 at the stage of static initialization, which occurs before any other initialization occurs. Then later at runtime, it is dynamically initialized with the value returned by factorial() .
This means that global objects can be initialized twice: once with static initialization (which is zero initialization), and later, at run time, they can be dynamically initialized.
Nawaz May 10 '11 at 6:11 2011-05-10 06:11
source share