Section 1.10 of “The
C Programming Language” by Brian
Kernighan and Dennis Ritchie aka K&R
looks at the scope of variables in C. There is a difference between a variable
declared inside a function and outside. The first is confined to the function
in which it is declared. It exists only when the function is called and dies
when the program leaves the function. Static variables are discussed elsewhere
and provide an except. The other is global in scope and created when the
program begins. It can be accessed by any function.
The sample code from 01x13
is modified to use global variables.
The variables are declared as they were in the functions but
are placed at the top of the source file (i.e., outside of any function).
The functions contain the same variable “declarations”
except the keyword extern is
added in front.
I haven’t seen it used a great deal for a couple of reasons.
As long as the program is running, these global variables take up memory even
if they won’t be used again. A key objective should be to use a little RAM as
possible. Second, global variables can be changed in ways that make debugging
difficult. It can lead to unexpected results. I avoid using them, but they do
serve a purpose at times.
Sample Code.
I am using Visual C++ 2010 and created the sample code as a
console application.
//
Function prototype.
int
getline();
void
copy();
// The
standard library includes the system function.
#include <cstdlib>
//
Standard I/O library.
#include <cstdio>
#define MAXLINE 1000 /* maximum input line length */
int
max; /* maximum length seen so far */
char
line[MAXLINE]; /* current input line */
char
longest[MAXLINE]; /* longest line saved here */
int main()
{
int len; /* current line length */
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);
// Keep console
window open.
system("pause");
// Return some
value.
return 0;
} // end main
/*
getline: read a line into s, return length */
int
getline()
{
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:
copy 'from' into 'to'; assume to is big enough */
void
copy()
{
int i;
i = 0;
extern char line[], longest[];
while ((longest[i] = line[i]) != '\0')
++i;
}
Output.
The longest line is…
No comments:
Post a Comment