博客首页 注册 建议与交流 排行榜 加入友情链接
推荐 投诉 搜索: 帮助

projwang

一个能思想的人,才真是一个力量无边的人
projwang.cublog.cn


Scope;External Variables
  An external variable has to be defined outside of any function; this allocates actual
storage for it. The variable must also be declared in each function that wants to access it, this may be done either by an explicit extern declaration or implicitly by context. For Example:

#include <stdio.h>
#define MAXLINE 1000

int getline(void);
void copy();
char line[MAXLINE];
char save[MAXLINE];
int max;

int main(void)
{
    int len;
    extern int max;
    extern char save[];

    max  = 0;
    while((len = getline()) > 0)
    {
       if(len > max){
          max = len;
          copy();
    }
    if(max > 0)
       printf("%s", save);
    return 0;
}

int getline(void)
{
    int c, i;
    extern char line[];
   
    for(i = 0; i < MAXLINE - 1
            && (c = getchar()) != EOF &&  c !=  '\n';  ++i)
                 line[i] = c;
    if(c == '\n'){
       line[i] = c;
       ++i;
    }
    line[i] = '\0';
    return i;
}

void copy(void)
{
    int i;
    extern char line[], save[];

    i = 0;
    while((save[i] = line[i] != '\0')
       ++i;
}

注:在某些情况下,extern 声明可以省略:如果一个变量的extern定义发生在它被使用之前。
但是如果程序是在多个源文件中,如defined the variable in file1 and used in file2
 then an extern declaration is needed in file2.
         

发表于: 2007-10-16 ,修改于: 2007-10-16 12:16,已浏览212次,有评论0条 推荐 投诉


网友评论

发表评论