C/C++中static关键字的使用

laughsky 2002-05-22 02:55:53
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).
例子:
test.h:
static int sVar2;
int Test1()
{
static int sVar1 = 10;
sVar1*=2;
return sVar1;
}
test.cpp
#include "stdio.h"
#include "test.h"

// sVar2 = 10; // 这里调用会编译出错 ??◎疑问1
int main(int argc, char* argv[])
{
sVar2 = 10; // 在VC++中,sVar2的确没有出现在WorkSpace->ClassView->Globals的变量表中,但却在main中
// 可以调用。◎疑问2??
printf("Test1()=%d\n", Test1());
printf("Test1()=%d\n", Test1());
printf("Test1()=%d\n", Test1());
printf("sVar2= %d\n", sVar2);
return 0;
}

VC执行结果:
Test1()=20
Test1()=40
Test1()=80
sVar2= 10

疑问1:sVar2为什么不能在test.cpp中main()之外不能使用
疑问2:MSDN说static修饰的变量不能在其文件之外可见,可在test.cpp中main()里可以使用,这又是为什么?
疑问3:用static修饰的函数到底有什么特点?
...全文
98 6 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
ajiefudan 2002-05-22
  • 打赏
  • 举报
回复
1 的问题也不对,不是main()不能使用,而是不在执行区间不能使用。
你再声明一个函数,在函数内部使用sVar2肯定不会用问题。
现在的情况即使sVar2是在test.cpp中声明,在 sVar2=10这里还是一样编译不通过
liem 2002-05-22
  • 打赏
  • 举报
回复
在函数外部使用变量标识,是声明
已经声明了static int sVar2;
在函数外部再用sVar=2;就是重复定义了。编译当然通不过。
fat_horse 2002-05-22
  • 打赏
  • 举报
回复
呵呵,当然是这样了。
比如你在test.h中这亲写:
static int sVar2;
sVar=2;
注意:这可不是在执行区间啊。:)
laughsky 2002-05-22
  • 打赏
  • 举报
回复
to lioneagle(LionEagle),
把sVar2定义在test.h中是我故意写的,看了你的回答我明白了一些,但是“疑问1”还是没有得到明确的解释,如果在main()外改变sVar2的值,VC编译器会给出如下错误:
error C2501: 'sVar2' : missing storage-class or type specifiers
error C2086: 'sVar2' : redefinition

大家不妨试试是不是这样
LionEagle 2002-05-22
  • 打赏
  • 举报
回复
在某个模块(.c文件)中定义的static变量作用域只在该模块内,别的模块不能用

你的static int sVar2;是定义在test.h里的,而test.cpp包含了test.h
相当于在test.c中定义了static int sVar2;这样做不好,如果test.h再被别的.c包含,就相当于分别在这两个.c中均定义变量static int sVar2,而这两个变量是互不干扰的。
对于全局变量一般定义在.c文件中(局部全局量,即加static的也是这样)

举个例子:

#include "stdafx.h"
#include "A.h"
#include <stdio.h>

int main(int argc, char* argv[])
{
x = 10;
f();
printf( "main.c x=%d\n",x );
f();
return 0;
}

// A.cpp

#include "stdafx.h"
#include "A.h"
#include <stdio.h>

void f()
{
x = 100;
printf( "A.c x=%d\n",x );
}

// A.h
#ifndef A_H
#define A_H

static int x;

void f();

#endif

输出为:

A.c x=100
main.c x=10
A.c x=100
Press any key to continue

123123123 2002-05-22
  • 打赏
  • 举报
回复
1错了吗

70,024

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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