|
|
|
|
 c语言static详解 - sixpeople [ 2006-07-06 20:50 | 3,003 byte(s)]
 Re: c语言static详解 - grip2 [ 2006-08-03 11:06 | 133 byte(s)]
 Re: c语言static详解 - magic8421 [ 2006-07-17 18:35 | 15 byte(s)]
 Re: c语言static详解 - zxm927 [ 2006-07-11 20:23 | 34 byte(s)]
 Re: c语言static详解 - shy828301 [ 2006-07-12 14:43 | 47 byte(s)]
 Re: c语言static详解 - IN_FLAMES [ 2006-07-12 08:47 | 22 byte(s)]
 不介意的话 请以后把帖子的内容也都发出来 谢谢 - teawater [ 2006-07-06 23:00 | 0 byte(s)]
|
|
|
|
[Original]
[Print]
[Top]
|
http://www.heloworld.org/bbs/viewtopic.php?t=43
c语言中static关键字有两个作用,一是文件作用域,二是函数作用域。
一、文件作用域
文件作用域关键字static的作用是,以static申明的全局变量、函数不得被其他文件所引用,例如:
//这是mystr.c文件的内容
#include <string.h>
static int num = 10;
int mynum = 100;
static int str_len(char *str)
{
return strlen(str);
}
int mystr_len(char *str)
{
return str_len(str) + num;
}
当你mystr.c文件中的str_len函数加上了static关键字,你便不能在其他的地方复用这个函数,譬如,你不能这样写:
//这是main.c 的内容
#include <stdio.h>
int main()
{
int len;
len = str_len("hello, world
");
printf("%d %d
", num, len )
return 0;
}
gcc main.c mystr_len.c
将不能编译通过,因为mystr.c中的num变量和str_len函数都用了static关键字,导致他们只能在mystr.c中被使用,如文件中的mystr_len函数可以引用num变量和str_len函数。
//这是main.c 的内容
#include <stdio.h>
int main()
{
int len;
len = mystr_len("hello, world
");
printf("%d %d
", my_num, len )
return 0;
}
当不用static关键字时,等同于extern,即
int mystr_len(char *str)
{
return str_len(str) + num;
}
和
extern int mystr_len(char *str)
{
return str_len(str) + num;
}
是一样的。
二、函数作用域
static另外一个用途是函数内部静态变量,最常用的情况是
int *test()
{
int num = 100;
int *ptr = #
return ptr;
}
int main()
{
printf("%d
", *test);
return 0;
}
该函数返回整数num的指针,在main函数中打印*test将会出现段错误,因为num做为test函数内部,只能在test内部被访问。以下程序是正确的。
int *test()
{
static int num = 100;
int *ptr = #
return ptr;
}
int main()
{
printf("%d
", *test);
return 0;
}
该程序中num变量加了关键字static,函数运行结束后,依然可以在其他地方被引用,只是不能直接通过变量名访问,而要间接通过指针访问,原因是 static变量存储在全局数据段中而不是函数栈中。读者可以将它看作特殊的全局变量,只是其他地方只能通过指针来访问,而不能直接通过变量名访问。
|
|
|
----
|
|
[Original]
[Print]
[Top]
|
|
[Original]
[Print]
[Top]
|
|
你的说法有问题。C中static是一个Storage-class specifiers,它的作用有两个(不考虑其他的扩展),一个是作用域的限制,一个是指定存储方式。
|
|
|
----
Simply the best
|
|
[Original]
[Print]
[Top]
|
|
|