A storage
class defines the scope (visibility) and life time of variables and/or
functions within a C /C++ Program.
Types of Storage Classes
Auto
Auto is the default storage class
for all local variables.
Register
Register is used to define local
variables that should be stored in a register instead of RAM. This means that
the variable has a maximum size equal to the register size (usually one word)
and can’t have the unary '&' operator applied to it (as it does not have a
memory location). Register should only be used for variables that require quick
access - such as counters.
It should also be noted that defining 'register'
goes not mean that the variable will be stored in a register. If registers are
busy or already occupied then it will be used as auto variables but as soon as
the registers are free it will be converted to register class
Static
Static is the default storage
class for global variables. Static variables can be 'seen' within all functions
in this source file. Static can also be defined within a function. Static
variables are initialized with 0 as default.
If this is done the variable is
initialized at run time but is not reinitialized when the function is called.
This inside a function static variable retains its value during various calls.
Extern
Extern is used to give a
reference of a global variable that is visible to ALL the program files. When
you use 'extern' the variable cannot be initialized as all it does is point the
variable name at a storage location that has been previously defined.
When you
have multiple files and you define a global variable or function which will be
used in other files also, then extern will be used in another
file to give reference of defined variable or function. Just for
understanding extern is used to declare a global variable or
function in another file.
A short
comparison of storage classes to give you a overview
Names
|
Automatic(default)
|
External
|
Static
|
Register
|
Lifetime
|
Function
block
|
Entire
program/global
|
Entire
program/global
|
Function
block
|
Visibility
|
local
|
Global
|
local
|
Global
|
Initial
value
|
Garbage
|
0
|
0
|
Garbage
|
Storage
memory
|
Stack
segment
|
Data
segment
|
Data
segment
|
CPU
registers
|
Purpose
|
For local
variables in class.
|
Those
variables which we might/or use throughout the program.
|
Local
variables which return their value, and retain the value even if the program
is rerun.
|
Variables
used for temporary calculations and stored in cpu registers for faster
access.
|
Keyword
used
|
Auto/(blank)
|
Extern
|
Static
|
register
|
0 comments:
Post a Comment