Just above and below main()
Wolfram Roesler
wolfram at cip-s08.informatik.rwth-aachen.de
Fri Apr 12 22:16:15 AEST 1991
stealth at nanometrics.portal.UUCP (Steve Sabram) writes:
>_________________________
>int outside;
>main()
>{
>int inside;
>...
>}
>_________________________
>We all agree that "outside" is
>a global and thus accessable Exactly.
>to all functions in this file
>while "inside" is accessable
>only to everything in main().
>Our debate is which one of these
>two are initialized to zero if
>any.
None of them is. The major difference is that the vars lie in different places
in memory. Outside is placed in the data segment of the program and inside in
on the heap of the funtion main. None of both is intialised to anything unless
you tell cc to do so:
int outside=0;
will initialise outside to 0 on prg start, and
int inside=0;
will initialise inside to 0 whenever main is called (ok main is called only
once but this is valid for other functions too of course).
To make inside keep its value during multiple calls of the function it is
in, use
static int inside=0;
this will place inside in the data seg just like it was a global, but it will
be accessible from the function it is in only. The initialisation will take
place only once at the start of the prg.
This is a highly recommended way to avoid globals.
More, the outside variable is not only accessible from all functions of the
file it is in but from all files linked together. The other files simply have
to say
extern int outside;
and they can do all they want to the variable. To hide outside from other
modules and to make it accessible to the current file only, use
static int outside;
For further info RTFM.
Hope to have helped you
Okami-san
More information about the Comp.lang.c
mailing list