the_init wrote On 02/12/07 13:37,:
Hi friends,
Can you please explain me why the following code prints 10, instead of
20 - Here I am little confused with the static and global declaration
of i in the same program.
#include<stdio.h>
int i;
This declaration of `i' is "visible" from here to the
end of the module, except where "hidden" by another
declaration of `i'.
int foo();
int print();
int main(void)
{
i = 10;
Only one declaration of `i' has been seen so far, so
this reference is to that `i', namely, the `i' declared
at file scope.
foo();
return 0;
}
int foo()
{
static int i = 20;
This declaration of `i' is visible from here to the
end of its containing block, namely, the end of the function
foo(). In that scope, it "hides" or "shadows" the file-scope
declaration of `i': `i' now refers to this inner variable and
there is no name that can refer to the file-scope variable.
print();
return 0;
}
At the end of foo(), the inner declaration of `i' goes
out of scope, and `i' regains its former meaning: it now
refers to the file-scope variable.
int print()
{
printf("%d", i);
The only visible declaration of `i' is the one for the
file-scope variable, so that is the `i' whose value is printed.
return 0;
}
--
Er*********@sun.com