Section 1.10 External Variables and Scope

Program

#include <stdio.h>
#define MAXLINE 1000 /* maximum input line size */
int max; /* maximum length seen so far */
char line[MAXLINE]; /* current input line */
char longest[MAXLINE]; /* longest line saved here */
int getline(void);
void copy(void);
/* print longest input line; specialized version */
main()
{
    int len;
    extern int max;
    extern char longest[];
    max = 0;
    while ((len = getline()) > 0)
        if (len > max) {
            max = len;
            copy();
        }
if (max > 0) /* there was a line */
        printf("%s", longest);
        return 0;
    }
/* getline: specialized version */
    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;
}
/* copy: specialized version */
void copy(void)
{
    int i;
    extern char line[], longest[];
    i = 0;
    while ((longest[i] = line[i]) != '\0')
        ++i;
}
Run this

Explanation

This program is same as finding the length of the longest line. The special thing here is we use external variables declared outside of any functions in the program and reference them within the functions by using the type extern. Here we see the integer max, strings line and longest declared outside of the main function, and those variables are referenced using extern type in main, getline and in copy function so that all these functions act upon the same variable. That is the reason, unlike the previous programs, we do not send the line and the longest as arguments to getline and copy, and neither we have to return the length from getline, because sharing of those is accomplished by sharing of the variable themselves.

Comments by Disqus