Hi,
I'm gonna keep it short and straightforward because I'm sure I'm missing something really obvious and also I have plenty of more advanced stuff to learn but my stupid brain just doesn't let these small details go.
Basically what I don't understand in the code below is why doesn't 'x' go back to 10 when the function is called a second time by the 'cout'.
1 2 3 4 5 6 7 8 9 10 11 12 13
int &fun()
{
staticint x = 10;
cout << x << endl;
return x;
}
int main()
{
fun() = 30;
cout << fun();
return 0;
}
It does cuz to me that doesn't look the same as the original code because x is initialised only once. Why is it not the same thing as this for example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
int x = 10;
int& fun()
{
x = 10;
std::cout << x << '\n';
return x;
}
int main()
{
fun() = 30;
std::cout << fun() << '\n';
}
Edit: Or at least why doesn't it produce a redefinition error (original code)?
I made a mistake. You're right that they are not "exactly the same except for scope" as I said above. But the only difference is when the initialization takes place.
The global one is initialized before main is called.
The static one is initialized the first time fun is called but never again afterwards.