Local/static variable scope in C++

2019-04-02 01:40发布

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?

5条回答
姐就是有狂的资本
2楼-- · 2019-04-02 02:22

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.

查看更多
Ridiculous、
3楼-- · 2019-04-02 02:23

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.

查看更多
beautiful°
4楼-- · 2019-04-02 02:31

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.

查看更多
forever°为你锁心
5楼-- · 2019-04-02 02:39

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;
}
查看更多
放荡不羁爱自由
6楼-- · 2019-04-02 02:40

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.

查看更多
登录 后发表回答