S
somenath
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();
cout<<"Val is: " <<val<<endl;
}
return 0;
}
Here the "val" variable is initialized multiple times. 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.
I tried to get answer by looking into the document “n1905” but did not get any help.
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();
cout<<"Val is: " <<val<<endl;
}
return 0;
}
Here the "val" variable is initialized multiple times. 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.
I tried to get answer by looking into the document “n1905” but did not get any help.