Local/static variable scope in C++(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++ 中的局部/静态变量作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 中的局部/静态变量作用域


基础教程推荐
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 在 C++ 中计算滚动/移动平均值 2021-01-01