为什么静态类的默认值为零? [英] Why the default value of static class is zero?

查看:96
本文介绍了为什么静态类的默认值为零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这与将静态存储在数据部分中有关还是与编译器有关???

解决方案

假设你的意思是变量而不是类,因为C没有; t有任何类的概念,你的所有问题都标记为(并且似乎与C相关)而不是C ++或C#!



主要依赖于编译器。

在C中, static 有两种用途,具体取决于变量的声明位置。

1)函数外部。在这种情况下,一切都是这个变量只能在这个文件中访问:文件外面没有任何东西可以看到它。这意味着您可以在不同的文件中使用两个具有相同名称的变量,并且它们不会相互干扰。

2)在函数内部。在这种情况下,它表示无论调用函数多少次,它总是获得变量的相同实例:这意味着如果函数更改了值,则下次调用它时它将具有新值。你需要在这里非常小心 - 这在多线程应用程序中非常危险!



初始值取决于编译器,就像它对所有其他变量一样。


阅读本文:

http://stackoverflow.com/questions/3373108/why-are-static-variables-auto-initialized-to-zero [ ^ ]

http://www.geeksforgeeks.org/g-fact-53/ [ ^ ]



-KR

Is this related to storing the static in data section or is it compiler dependent??

解决方案

Assuming you mean "variable" not "class" as C doesn;t have any concept of classes and all your questions a tagged as (and appear to related to) C rather than C++ or C#!

Compiler dependant, mostly.
In C, static has two uses, depending on where the variable is declared.
1) Outside a function. In this case, all is does is say "this variable is only accessible within this file: nothing outside the file can see it". Which means that you can have two variables with the same name in different files, and they won't interfere with each other.
2) Inside a function. In this case, it says that no matter how many times the function is called, it always gets the same instance of the variable: which means that if your function changes the value, the next time it is called it will have the new value. You need to be very careful here - this is very dangerous in multi threaded applications!

The initial value depends on the compiler, just as it does for all other variables.


Read this:
http://stackoverflow.com/questions/3373108/why-are-static-variables-auto-initialized-to-zero[^]
and http://www.geeksforgeeks.org/g-fact-53/[^]

-KR


这篇关于为什么静态类的默认值为零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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