What do you mean by dynamic initialization of a variable? Give an example?
|Subject||Object Oriented Programming|
|NU Year||Set: 1.(d) Marks: 3 Year: 2015|
According to the C/C++ standards global variables should be initialized before entering main(). In the above program, variable 'i' should be initialized by return value of function alpha(). Since the return value is not known until the program is actually executed, this is called dynamic initialization of variable.
Let us compile the above program and link with entrypoint ‘main’.
cl Foo.cpp /link /entry:main
Here’s your output when you run the exe –
i = 0
Surprised? We all expected the output to be -”i = 20”. Let us try to understand why we got an unexpected output.
The global ‘i’ has a dynamic initializer, so its value is not initialized until the program is executed. Since we linked the exe with entrypoint as’ main’, the C Runtime started executing ‘main()’ as the first function in your program. ‘alpha()’ was never invoked and ‘i’ was never initialized, hence the unexpected output.
Now the question is how do we invoke these dynamic initializers before ‘main()’ and still keep the entry point of our program as ‘main()’?