Search code examples
c++variablesstaticscope

Local/static variable scope in C++


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?


Solution

  • 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.