Scope of 'static' variables

Peter Holzer hp at vmars.tuwien.ac.at
Tue Nov 27 03:56:07 AEST 1990


elee6i5 at jetson.uh.edu writes:


>When you use 'static' to initialize an array in side a fn,
>as in static int data[3] = {1,2,3}; the array is initialized
>before the program runs. Since this can't be allocated on the 
>stack frame, it has to be allocated  on the data segment(?).

>But how is 'scope' preserved for such static variables 
>declared inside a function ?

The variable is only visible inside the fuinction it is defined
(exactly: inside the block it is defined) but it exists even
when the function is not active (so you can pass a pointer to it
to the calling function which can manipulate it).

>Could any one explain this ,with reference to  ix86 architecture?

The static variables usually get names which cannot clash with
other variables (something like L0001 (or just
BeginDataSegmentOfThisModule + Offset), C external variables are
prefixed with an underscore), and are not exported to other
modules. So static variables are just like globals but no other
function knows its name, so it cannot be referenced (except
through a pointer).

Turbo C does it this way, and all other compilers I know do it
similarly.
--
|    _  | Peter J. Holzer                       | Think of it   |
| |_|_) | Technical University Vienna           | as evolution  |
| | |   | Dept. for Real-Time Systems           | in action!    |
| __/   | hp at vmars.tuwien.ac.at                 |     Tony Rand |



More information about the Comp.lang.c mailing list