函数内部和外部静态变量的区别?
static int count;
int main()
{
static int count;
}
在函数内部和外部声明的静态变量有什么区别吗?
(我的意思是变量计数的范围和可见性)
static int count;
int main()
{
static int count;
}
Is there any difference between static variables declared inside and outside any function?
(I mean the scope and visibility of the variable count)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当您在方法外部声明时,它将可用于声明后编写的所有
静态方法函数。在方法中声明静态变量时,仅该方法可以访问。When you declare outside of method it will be available to all
static methodfunctions written after its declaration. While declaring static variable in method will be accessible by only that method.全局变量的动态初始化也存在差异(请参阅此处)。总而言之,如果您有:
执行 main 时将调用“foo”,但标准(C++“03”)根本不需要调用“bar”!
There's also a difference in dynamic initialization of globals (see here). To summarize, if you had:
The call to 'foo' will take place when main is executed, but the standard (C++ '03) doesn't require a call to 'bar' at all!
您的第一个
count
只能在模块内访问(该文件中的代码)。您的第二个count
只能在main
中访问。Your first
count
is only accessible within the module (code in that file). Your secondcount
is only accessible withinmain
.