Shraddha wrote On 06/25/07 09:25,:
Can we declare extern variable as static?
What will be the scope of the variable then? What if we change the
value of the variable in some other function?
Also can someone tell me that if we can declare the global
variable...and it is having scope throughout the file then what is so
different in extern variable???
You seem to be confused about the two different
notions of "scope" and "linkage." (This confusion is
understandable, in part because people throw the word
"scope" around in sloppy fashion.)
In C, the scope of an identifier is the part of a
translation unit ("module" or "compilation") where a
particular declaration of the identifier is in force.
Different kinds of declarations have different scopes
that obey different rules: For example, the scope of
a variable or function declared inside a { } block ends
at the closing }, while the scope of a declaration that
is outside any block extends to the end of the module.
Scopes may be "interrupted" by competing declarations:
int foo;
void bar(void) {
long x = foo; /* referring to the int */
double foo = 9; /* a competing declaration */
printf ("%g\n", foo); /* refers to the double */
}
void baz(void) {
printf ("%d\n", foo); /* refers to the int again */
}
There are two different declarations of `foo' here. The
scope of the first one starts at its declaration and
runs to the end of the whole module, but is interrupted
by the second declaration inside bar(). The scope of
the second `foo' starts at *its* declaration and runs
to the closing } at the end of the block, at which point
the scope of the original `foo' resumes.
Linkage is an entirely different matter. It governs
whether identical identifiers in different scopes refer
to the same object/function or to unique ones. When an
identifier has "external linkage," all its scopes in all
the program's translation units are gathered together and
made to refer to the same thing. When an identifier has
"internal linkage" or "no linkage," the scopes are kept
apart: Each scope's use of the identifier refers to its
own unique object or function.
"Global variable" is a loose and undefined term; you
can use it informally but should avoid it when you need
to discuss something precisely.