Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 965
George Irimiciuc Avatar asked Mar 01 '13 07:03

George Irimiciuc


2 Answers

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.

like image 86
Benjamin Lindley Avatar answered Oct 05 '22 03:10

Benjamin Lindley


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.

like image 30
Messy Coder Avatar answered Oct 05 '22 02:10

Messy Coder