If I write something like this:
#include <iostream>
int main()
{
using namespace std;
{int n;n=5;} cout<<n;
system("pause");
return 0;
}
The compiler tells me that n is undeclared. Then I tried making it static, but again, the compiler tells me that it is undeclared. Doesn't a variable declated static have program scope? If not, how do I use n in this program?
You're confusing scope with lifetime. Static variables have a lifetime equal to the program's lifetime, but they still follow scoping rules based on where they are declared.
The scope of n is just between the brackets:
{int n;n=5;}
so outside of the block, you have no n variable.
Making it static just makes it's value retain even after you exit the block so that the next time you enter that block again, you can retrieve it's value from the last time you executed that block, but still it's scope is still within the brackets.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With