Any Software Program = Instructions + data
C Program = Statements + Variables
In a C program, statements are placed inside a function
hence, we conclude, C program = Functions + Variables
Functions:
Global
Static
Variables:
Constant
Global
o extern
o static
Local
o auto
o register
o static
Storage Class
A storage class defines the scope (visibility) and life-time of variables and/or functions within a C
Program.
To specify the storage class, We use the below listed keywords:
auto
o Refers to Local variables.
o This is default storage class of a local variable
o Scope: Within the function
o Life time: Alive only during function call. Otherwise it is dead.
o Gets re-initialized for every function call
o Default value: unknown (garbage)
o Memory Segment: Stack
register
o Refers to local variable.
o With this keyword, we request complier to allocate CPU register(s) for the
specified variable(s) for quick read/ write.
o Compiler may or may not do this. It depends on overall memory organization and
OS architecture.
static
o can be use used for:
Functions
To restrict the function to be used in the same .c file only.
Global Variables
To restrict the variables to be used in the same .c file only
Scope: Within the same .c file
Local Variables
Scope: Within the Function
Life: Alive throughout the program
Default Value: 0
Memory Segment: Initialized Data Segment
Does not get re-initialized for each function call
extern
o Can be used for
Functions
Declaring a function with extern makes it globally accessible in any
part of the program.
Global Variables
Declaring a global variable with extern makes it globally accessible in
any part of the program.
Memory Segment of Global Variables: Read Write Data Segment
const
o Generally used with global variables.
o A variable specified with const keyword is a Read Only.
o It must be initialized with a value and can’t be modified further.
o Memory Segment: Read Only Data Segment.
Memory Layout of C Program
Command Line Arguments Higher Address
Stack Segment
Stack Frame for every function Call
Function Arguments
Local variables (auto)
return value/ address
Stack grows toward lower address
Heap Segment
(Dynamically allocated memory blocks with
malloc()/ calloc())
heaps grows towards higher address
Read/ Write Data Segment
Uninitialized Data Segment (bss)
Initialized Data Segment
Read Only Data Segment
Code/ Text Segment
(Instructions part of the C program)
Lower Address