本文介绍了C ++中的本地/静态变量作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我写这样:

#include <iostream>

int main()
{
    using namespace std;

    {int n;n=5;} cout<<n;
    system("pause");
    return 0;
}

编译器告诉我n是未声明的。然后我试图使其静态,但是,再次,编译器告诉我,它是未申报。不是变量声明的静态有程序范围?

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.

这篇关于C ++中的本地/静态变量作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 01:22