C++ 中的局部/静态变量作用域 [英] Local/static variable scope in C++

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

问题描述

如果我这样写:

#include <iostream>

int main()
{
    using namespace std;

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

编译器告诉我 n 未声明.然后我尝试将其设为静态,但编译器再次告诉我它未声明.声明为静态的变量没有程序范围吗?如果不是,我如何在这个程序中使用 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++ 中的局部/静态变量作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆