Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Storage-class differences?

Tags:

c

memory

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?

like image 861
user319516 Avatar asked Apr 18 '10 06:04

user319516


1 Answers

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).

like image 54
TheCodeArtist Avatar answered Sep 20 '22 18:09

TheCodeArtist