On Saturday 31 January 2009 10:04:12 Saifi Khan wrote:
> Hi all:
>
> Here are two C++ programs.
>
> The first one doesn't work, while the second one does.
>
> // --------------------------------
>
> #include <iostream>
>
> int i;
> i = 5;
>
> int main(int argc, char *argv[])
> {
> return 0;
> }
>
> // --------------------------------
<< snipped >>
Saifi,
The compiler considers all statements outside of a scope to be
type or variable declarations. The variables can be initialized
along with their declarations eg. "int i =5;" will work.
Unless declared inside a scope, the expressions cannot get executed.
When do you expect the line "i=5" in the above code to get
executed ?
If your requirement is to do something at load time - before main() is
called, you can do that in the constructor of an object and
instantiate that object in global space.
Maybe C++ compilers should start supporting static blocks. Just a
thought.
Namita