Hi, guys. I was just now reading about local static object and really troubled by the mechanism of how a static object works. According to my textbook, a static object would have somehow been initialized even before the its definition is executed, which would indicate that if I use a static object in a user-defined function, then the static object I defined in the function will continue to exist until the program terminates. If this is true, please take a look at the following code
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
#include <iostream>
using namespace std;
int sequencef();
int main()
{
for (unsigned i = 0; i != 20; ++i)
cout << sequencef() << endl;
}
int sequencef()
{
static int i = 0;
return i++;
}
|
In the code above, I had variable i overloaded, and it's defined as a static int in function sequencef. As I understand, since i was defined as a static object, it would retain its existence even outside of this sequencef fucntion. However, in the main function body, I defined a variable with the same name i in a for loop. What I expected was that the compiler would get "confused" of this two 'i's, but it didn't, and it worked perfectly well as it's supposed to be ( to print numbers from 0 to 20).
Here's what I think. If the static int i defined in sequencef continues to exist even outside of sequencef, then it should exist in the main function body, which means when another i is defined in a for loop in the main function, there would be 2 'i's. Let's refer the 'i' in the sequencef as i.1 and the other 'i' as i.2 . So if we set our eyes on the scope of the for loop, if it's the i.2 playing its part in this scope, then i.2 should be printed as to be 10-30, which is not the case; if it's i.1 being the i here in this scope, the for loop should be functioning at all.
I'm really confused about in what scope a static object exist. I tried run the following code as well and it gave me a error saying that i was not declared, so I guess that there must be a certain scope in which the static objects retain their existence and it's not the main function body.
1 2 3 4 5 6 7 8 9 10 11 12 13
|
#include <iostream>
using namespace std;
int sequencef();
int main()
{
cout << i;
cout << sequencef();
int sequencef()
{
static int i = 0;
return i++;
}
|