Static vs. global

Do you have a question? Post it now! No Registration Necessary

Translate This Thread From English to

Threaded View



Hi, can anyone tell me the difference between a static and global
variable and how they effect the stack in the "C" language.

Thank You

Jim


Re: Static vs. global

Quoted text here. Click to load it

Within the scope of a function a static variable persists between function
calls just like any other global (it is not on the stack). However it is
only visible from within the function. The function could return a pointer
to the variable and it would be vaild when the function has returned.

Within the scope of a file, a static variable is like any other global
EXCEPT that it cannot be seen by the linker and cannot be accessed by
another module using the "extern" keyword. Again pointers to static
variables can be passed about - static does not make them impossible to get
at from outside a module just impossible to see using "extern".

try:

void fred(int val)
{
static int cnt = 0;

        printf("%d %d\n", cnt++, val);

}

main()
{
        int    j;

        for (j=3; j<13; j++)
        {
                fred(j);
        }
}


Regards
Sergio Masci

http://www.xcprod.com/titan/XCSB - optimising structured PIC BASIC compiler



Re: Static vs. global
Thanks for the explanation

Jim

Sergio Masci wrote:
Quoted text here. Click to load it


Re: Static vs. global

Quoted text here. Click to load it

Think of it this way, static always means the variable exists for the life
of the program and its scope is restricted to the enclosing file or block,
which ever is the tighter scoping.

--
- Mark ->
--

Site Timeline