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

gyscsdn 2003-01-15 04:24:40
请问在C语言中的static 变量和函数是什么意思?
...全文
629 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
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
  • 打赏
  • 举报
回复
表示这个函数或者变量是静态的,且其只能在本文件被调用。别处的修改会对其产生影响。

24,854

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 工具平台和程序库
社区管理员
  • 工具平台和程序库社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧