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.
how do I use n in this program?
using namespace std;
int main()
{
int n; // declare n as int
n=5; // assign it a value
cout << n; // display it.
system("pause");
return 0;
}
A variable declared static in the global scope has its scope limited to the translation unit. A variable declared static within a function has its lifetime set to be the same as the program's, but in this case does not affect its scope. You will have to put cout
in the same scope as n
was declared in order to use it.
Here the compiler gives error n is undeclared because here "{int n;n=5;}" it is declared in the braces. And braces tells us about the scope of the variable. When ever the scope ends the variable is deleted from the memory.
And for Static and local.
Static : The variable is same like global variable but its value remains constant throughout the application. And the static variable cannot be used on the other page using extern.
Local : The local variables are stored in the stack and they are deleted when they get out of scope.