C programming

akhz
4 pages
akhz
4 pages
61
/ 4
Storage Class in C
C storage classes define the scope (visibility) and lifetime
of variables and/or functions within a C Program.
 Basic Concepts
Before diving into storage classes, let’s understand a few essential terms:
 1. Scope
Defines where the variable is accessible.
It’s a block or region where the variable is declared
Types:
o Local Scope: Inside a block or function.
o Global Scope: Available throughout the file or program.
 2. Storage
Refers to where in memory the variable is stored:
o Stack: Temporary memory for local variables.
o Heap: Dynamically allocated memory.
o Data Segment (Static/Global Area): Memory for static and global variables.
o CPU Register: Very fast, small storage.
 3. Lifetime
Determines how long the variable exists in memory.
o Temporary: Removed after function/block execution.
o Persistent: Exists for the program’s entire execution.
 Storage Classes in C
C has four main storage classes: auto, extern, static, and register.
They control a variable’s scope, lifetime, storage location, and default initialization.
Summary Table
Storage
Class
Keyword
Scope Lifetime Memory Location
Default
Value
Automatic
auto
Local Function/block
Stack
Garbage value
External
extern
Global Entire program
Data Segment
Zero (0)
Static
static
Local/Global
Entire program
Data Segment
Zero (0)
Register
register
Local Function/block
CPU Register /
Stack
Garbage value
 1. auto (Automatic Storage Class)
Default storage class for local variables.
Exists only during function execution.
Stored in the Stack.
Not accessible outside the block.
Initialized with a garbage value.
void display()
{
auto int x = 10; // same as int x = 10;
printf("%d", x);
}
 2. extern (External Storage Class)
Used to declare a global variable defined elsewhere.
Stored in the Data Segment.
Lifetime is entire program execution.
Useful for multi-file programs.
extern int count; // Declaration only
int main()
{
printf("%d", count); // Uses count defined elsewhere
}
// Defined in another file
int count = 5; // Allocated in Data Segment
 3. static (Static Storage Class)
Retains value between function calls.
Stored in the Data Segment (even if defined locally).
Lifetime is entire program.
Initialized only once, default = 0 if not explicitly assigned.
#include <stdio.h>
void demo()
{
static int count = 0; // static variable
count++;
printf("Count is %d\n", count);
}
int main()
{
demo(); // Call 1
demo(); // Call 2
demo(); // Call 3
return 0;
}
Each call to demo() will remember the previous value of n.
 4. register (Register Storage Class)
Suggests storing the variable in a CPU Register for fast access.
If registers are unavailable, compiler may use Stack.
Cannot access the address using &.
Useful for loop counters, frequently accessed variables.
void fastLoop()
{
register int i;
for (i = 0; i < 10; i++) {
printf("%d ", i);
}
}
 Key Differences in Memory
/ 4
End of Document
61