请问在C语言中的static 变量和函数是什么意思?

gyscsdn 2003-01-15 04:24:40
请问在C语言中的static 变量和函数是什么意思?
...全文
347 点赞 收藏 8
写回复
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
lizhiwo_wo 2003-01-15
please read the book carefully.
回复
despider 2003-01-15
static函数表示只能被当前文件调用
static变量, 给你举个例子:

void f()
{
static int i=0;
i++;
cout<<i<<endl;
}
void main()
{
for (int i=0; i<5; i++)
{
f();
}
}
输出:
1
2
3
4
5
回复
qing_li73 2003-01-15
static
static declarator

When modifying a variable, the static keyword specifies that the variable has static duration (it is allocated when the program begins and deallocated when the program ends) and initializes it to 0 unless another value is specified. When modifying a variable or function at file scope, the static keyword specifies that the variable or function has internal linkage (its name is not visible from outside the file in which it is declared).

In C++, when modifying a data member in a class declaration, the static keyword specifies that one copy of the member is shared by all the instances of the class. When modifying a member function in a class declaration, the static keyword specifies that the function accesses only static members.

For related information, see auto, extern, and register.

Example

// Example of the static keyword
static int i; // Variable accessible only from this file

static void func(); // Function accessible only from this file

int max_so_far( int curr )
{
static int biggest; // Variable whose value is retained
// between each function call
if( curr > biggest )
biggest = curr;

return biggest;
}

// C++ only

class SavingsAccount
{
public:
static void setInterest( float newValue ) // Member function
{ currentRate = newValue; } // that accesses
// only static
// members
private:
char name[30];
float total;
static float currentRate; // One copy of this member is
// shared among all instances
// of SavingsAccount
};

// Static data members must be initialized at file scope, even
// if private.
float SavingsAccount::currentRate = 0.00154;
回复
gyscsdn 2003-01-15
CACHE2002
能举例说明说明一下吗?
谢谢!
回复
cache2002 2003-01-15
在子函数中STATIC是静态变量类型定义,这样在使用时,每次调用子函数,该变量的值保持上一次的结果,即按上一次计算得出的结果进行本次函数的处理。
回复
sayaza 2003-01-15
这要看你写在哪里。在所有函数之前,那就是全局变量,但static表示只能在当前文件被调用。不加的话,当前工程中任何文件都能调用。如果调用中修改了它的值,新值会被保存下来。
回复
gyscsdn 2003-01-15
与全局有什么区别?都是别处的修改会对其产生影响?
回复
sayaza 2003-01-15
表示这个函数或者变量是静态的,且其只能在本文件被调用。别处的修改会对其产生影响。
回复
发动态
发帖子
工具平台和程序库
创建于2007-09-28

2.4w+

社区成员

C/C++ 工具平台和程序库
申请成为版主
社区公告
暂无公告