On Wednesday, January 23, 2013 12:47:15 PM UTC+5:30, Paavo Helde wrote:
> somenath <> wrote in
>
> news:cc92d31f-a0cc-49f8-8d37-:
>
>
>
> >
>
> > I have one question regarding the static variable in C++.
>
> > According to my understanding the static variable is initialized only
>
> > once. So is the following program valid?
>
> >
>
> > #include<iostream>
>
> > using namespace std;
>
> >
>
> > static char* getVal()
>
> > {
>
> > static char *s ="test";
>
> > return s;
>
> > }
>
> >
>
> > int main (void)
>
> > {
>
> > int i =0;
>
> > for (i =0;i< 1000;i++)
>
> > {
>
> > static char *val = getVal();
>
>
>
> Here you have 2 statics, where one is initialized from the other.
>
> Strictly speaking, this should not be necessary, one static should be
>
> enough to hold a long-living value. Now you have 2 long-living duplicates
>
> with the same value. But as written, this is not an error either.
>
>
>
> > cout<<"Val is: " <<val<<endl;
>
> > }
>
> > return 0;
>
> > }
>
> >
>
> > Here the "val" variable is initialized multiple times.
>
>
>
> No, it is not, it just looks so.
>
>
>
> > Though it is
>
> > printing the correct output every time I run this program but is this
>
> > behavior (trying to initialized static variable multiple times) well
>
> > defined?
>
> >
>
> > The reason for asking this question is ,the similar logic does not
>
> > provide correct result all the time when it is part of large program.
>
> > There, the "val" variable sometime gets empty string.
>
>
>
> Namespace level static initialization order fiasco? Multithreading?
> Neither is present in your example code so of course it runs as expected.
>
>
>
> The empty string probably comes from a static initialization step, which
>
> means that a static is used before the proper dynamic initialization is
>
> completed. Look up static and dynamic initialization in C++.
Many thank all of you for the response.
Yes the large program is multithreaded. But I am almost sure that is
not multi-threading issue.
I am not aware of “Namespace level static initialization order fiasco”
also not aware of “static and dynamic initialization” in C++.
I will try to learn it. If you could provide some more details it
will be very helpful.
Is “static and dynamic initialization” is not present in C?
|