Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
469 views
in Technique[技术] by (71.8m points)

memory - C Storage-class differences?

What is the difference between a variable declared as an auto and static? What is the difference in allocation of memory in auto and static variable? Why do we use static with array of pointers and what is its significance?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

AUTO (default), Static, Extern & Register are the 4 modifiers for a variable in C.


  • auto : The default storage-class for a C variable. (i.e. no need to explicitly specify auto).

  • static : Changes the lifetime of the variable. (retains the scope, no change).

This means, during runtime, the OS does NOT of delete the variable from memory once the function( containing the variable exits) and initialise the variable every time the function is called.

Rather the static variable is initialised ONLY the first time the function (containing it is called). Then it continues to reside in the memory until the program terminates. in other words STATIC effectively makes a variable GLOBAL in memory, but with only LOCAL access.

Where your statics are stored depends on if they are 0 initialized or not.

  • 0 initialized static data goes in .BSS (Block Started by Symbol),

  • non 0 initialized data goes in .DATA

One must note that, though static-variables are always in the memory, they can only be accessed ONLY from the local scope (function they are defined in).

  • extern : Used to signal to the compiler that the extern-definition is simply a placeholder, and the actual definition is somewhere else. Declaring a variable as extern will result in your program not reserving any memory for the variable in the scope that it was declared. It is also common to find function prototypes declared as extern.

  • register : Signals the compiler to Preferrably used a CPU-register (and not RAM) to store this variable. Used to improve performance, when repeated access to the variable is made (for ex: loop counter variables).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...