Storage Classes in C
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

Storage Classes in C Programming – Complete Guide for Beginners

📑 On this page:
  • Introduction
  • Characteristics of Storage Classes
  • Types of Storage Classes
  • Auto Storage Class
  • Register Storage Class
  • Static Storage Class
  • Extern Storage Class
  • Frequently Asked Questions
📚 In this tutorial, you will learn:
  • What are storage classes in C and why they are important
  • The four types of storage classes: auto, register, static, and extern
  • How scope, lifetime, memory allocation, and initial value work
  • Practical examples with code for each storage class
  • When to use each storage class in your programs

Introduction to Storage Classes in C

In this tutorial topic, we will learn in detail about the storage class in C, its types, and how its properties affect the output of the program along with some programming examples.

C programming puts a lot of importance on the use of variables in all programs. Every variable we declare in a C program has a scope and lifetime. Each variable in C has two properties: data type and storage class. The data type refers to the data of the variable, and the storage class determines the scope, visibility, and lifetime of the variable.

A storage class in C is used to define the lifetime, visibility, memory location, and initial value of a variable.

Characteristics of Storage Classes

A storage class in C defines the following characteristics of a variable:

  • a. Scope (Visibility): Indicates where the variable is accessible in the program and where it is not. The scope of a variable is determined only at compile time without creating any function call stack that occurs at runtime.
  • b. Lifetime: How long a variable stays in the appropriate location in system memory. It is the time between when memory is allocated to hold the variable and when it is freed. Once a variable goes out of scope, its lifetime expires.
  • c. Memory Allocation: Where functions or variables are stored in memory (CPU or RAM registers).
  • d. Initial Value: The default value assigned to the variable when it is declared.

💡 Key Point: Storage classes in C allot (allocate) a storage area for a variable that will be kept in memory. They are stored in the system's RAM. In addition to the storage location, they determine the scope of the variable.

Storage classes in C allot storage area for variables in system RAM

Types of Storage Classes in C

Storage classes or memory classes in C language are declared in a program or block with memory class specifiers:

  • auto - Automatic storage class
  • register - Register storage class
  • static - Static storage class
  • extern - External storage class

There is another storage class specifier, "typedef", used syntactically, which does not reserve memory. Specifiers instruct the compiler to store variables.

1. Auto Storage Class (Automatic)

This is the default storage class that holds the values or objects for all the variables that are displayed in the function or block. If a storage class is not specified, every variable defined in a function or block will default to the automatic storage class.

Therefore, the auto keyword is rarely used when writing C programs. Functions or block variables contained in the auto storage class are declared using the auto specifier. Variables in C are local to the block they are defined in and are discarded outside the block.

🔹 Auto Storage Class Features:

  • Keyword: auto
  • Scope: Local to the block in which declared
  • Lifetime: Until the block ends
  • Memory Allocation: Stack (RAM)
  • Initial Value: Garbage (undefined)

C Program Demonstrating Auto Storage Class

#include <stdio.h>

int main() {
    auto int v = 11;
    {
        auto int v = 22;
        {
            auto int v = 33;
            printf("%d ", v);
        }
        printf("%d ", v);
    }
    printf("%d", v);
    return 0;
}

Output:

33 22 11

Explanation:

  1. The variable v is declared three times in different blocks.
  2. The variable v with the same name is defined three times in different blocks.
  3. The program will compile and run successfully without any error.
  4. The printf() function in the innermost block prints 33, and variable v inside this block is destroyed after the block ends.
  5. This is followed by another block which prints 22, which is followed by a block which prints 11.
  6. Automatic variables are initialized correctly; otherwise, you will get undefined values because the compiler does not assign an initial value to them.

2. Register Storage Class

The register storage class is a required specifier that tells the compiler to store the object in a machine register. Variables defined as registers are allocated among CPU registers according to the size of memory remaining in the CPU.

When you want to store local variables in a function or block in CPU registers instead of RAM to get quick access to these variables, you can use the register storage class. The access time for register variables is faster.

🔹 Register Storage Class Features:

  • Keyword: register
  • Scope: Local to the block in which declared
  • Lifetime: Until the block ends
  • Memory Allocation: CPU register (if possible), otherwise stack
  • Initial Value: Garbage (undefined)
  • Note: Cannot use & (address-of) operator with register variables

C Program Demonstrating Register Keyword

#include <stdio.h>

int main() {
    register int a;  // Declaring 'a' as a register variable
    int b;
    
    a = 100;
    b = 200;
    
    printf("Value of a: %d\n", a);
    printf("Value of b: %d\n", b);
    
    return 0;
}

Output:

Value of a: 100
Value of b: 200

Explanation:

In the above example, we have defined a as a register variable. On the other hand, whether it is actually stored in a CPU register depends on the behavior of the compiler. The main thing you need to consider is that the register will not match the variables whose addresses are selected using the & operator, because it is not easy to directly deal with the register. Therefore, trying to apply registry changes results in a compilation error.

3. Static Storage Class

The static storage class defines a variable with a fixed lifetime. This means the variable is allocated in memory when the program starts and is deleted only after the program terminates. This means that the variable retains its value between function calls.

🔹 Static Storage Class Features:

  • Keyword: static
  • Scope: Local to the block in which declared
  • Lifetime: Throughout the entire program
  • Memory Allocation: Data segment
  • Initial Value: Zero (0)

C Program Demonstrating Static Storage Class

#include <stdio.h>

int statfunc() {
    static int tot = 40;
    tot++;
    return tot;
}

int main() {
    printf("total = %d \n", statfunc());
    printf("total = %d \n", statfunc());
    return 0;
}

Output:

total = 41
total = 42

Explanation:

  1. The statfunc() function has a variable called tot, initially set to 40.
  2. The static keyword is used to create a static variable, meaning that the variable's value will be conserved or preserved between function calls.
  3. The statfunc function increments the value of tot by 1 and then returns the new value.
  4. When statfunc() is called, it will always return the next value in the sequence (41, 42).
  5. In the main function, statfunc() is called twice, and the return value is printed using the printf function.

4. Extern Storage Class

The extern storage class is used when we have functions or global variables shared between two or more files. The word extern is used to define a global variable or function in another file to refer to a variable or function that is already defined in the original file.

Variables defined with the extern keyword are called global variables. These variables are available to access during the entire program. Note that an extern variable cannot be initialized because it is already defined in the original base file.

🔹 Extern Storage Class Features:

  • Keyword: extern
  • Scope: Global
  • Lifetime: Throughout the entire program
  • Memory Allocation: Data segment
  • Initial Value: Zero (0)

Example: Extern Storage Class

File1: main.c

#include <stdio.h>

extern int xt;

int main() {
    printf("The value of the external integer xt is = %d\n", xt);
    return 0;
}

File2: original.c

#include <stdio.h>

int xt = 48;

Output:

The value of the external integer xt is = 48

Summary of Storage Classes

Storage Class Keyword Scope Lifetime Memory Initial Value
AutoautoLocalBlock endStackGarbage
RegisterregisterLocalBlock endCPU RegisterGarbage
StaticstaticLocalProgram endData SegmentZero
ExternexternGlobalProgram endData SegmentZero

💻 Practice Exercise

Challenge: Write a program that demonstrates the difference between auto and static variables. Create a function that increments and prints a counter. Call the function multiple times and observe the output.

🔍 Click to Show Solution
#include <stdio.h>

void autoCounter() {
    int count = 0;  // auto variable - resets each time
    count++;
    printf("Auto: %d\n", count);
}

void staticCounter() {
    static int count = 0;  // static variable - retains value
    count++;
    printf("Static: %d\n", count);
}

int main() {
    printf("Auto Counter (resets each call):\n");
    autoCounter();
    autoCounter();
    autoCounter();
    
    printf("\nStatic Counter (retains value):\n");
    staticCounter();
    staticCounter();
    staticCounter();
    
    return 0;
}

/* Output:
Auto Counter (resets each call):
Auto: 1
Auto: 1
Auto: 1

Static Counter (retains value):
Static: 1
Static: 2
Static: 3
*/

Frequently Asked Questions About Storage Classes in C

1. What is a storage class in C?

A storage class in C defines the scope, lifetime, memory location, and initial value of a variable. It determines where and how long a variable exists in memory.

2. How many storage classes are there in C?

There are four storage classes in C: auto, register, static, and extern. There is also typedef, but it is not a storage class in the traditional sense.

3. What is the default storage class in C?

The default storage class in C is auto. If you don't specify a storage class, variables inside a function are automatically considered auto.

4. What is the difference between static and extern?

static variables are local to the file or function and retain their value between function calls. extern variables are global and can be accessed across multiple files.

5. When should I use register storage class?

Use register when you want fast access to frequently used variables, like loop counters. However, the compiler may ignore the request and store it in memory instead of a register.

💡 Tip: Understanding storage classes is essential for writing efficient and bug-free C programs. They help you control memory usage and variable accessibility.

📖 Related Tutorials

  • malloc in C - Dynamic Memory Allocation
  • calloc in C - Dynamic Memory Allocation
  • free in C - Dynamic Memory Deallocation
  • realloc in C - Resizing Memory

Previous Topic: -->> realloc() in C   ||   Next topic: -->> Graphics in C


📚 Explore More Topics

🗄️ SQL Interview Questions & Answers

SQL SELECT Statement FAQ SQL Restricting & Sorting Data FAQ SQL Group Functions & Aggregated Data FAQ SQL Multiple Tables (JOINs) FAQ SQL Subqueries FAQ SQL DML Statements (Managing Tables) FAQ SQL Indexes, Synonyms & Sequences FAQ SQL DDL (Tables & Relationships) FAQ SQL Views FAQ SQL Indexing Best Practices FAQ SQL Window & Analytic Functions FAQ

🐍 Python Interview Questions & Answers

Python Interview Questions Python Syntax & Variables FAQ Python Data Types FAQ Python If-Else FAQ Python Loops FAQ Python Functions Interview Q Python String Manipulation FAQ Python Lists & Dictionaries FAQ Python Tuples & Sets FAQ Python Exception Handling FAQ Python OOP Interview Questions

☕ Java Interview Questions & Answers

Java Introduction Interview Q Java Development Environment FAQ Java Data Types FAQ Java Control Flow & Operators FAQ Java Basic Input/Output FAQ Java Arrays FAQ Java Strings FAQ Java Methods FAQ Java Basic OOP Concepts FAQ Java Advanced OOP Concepts FAQ Java OOP Best Practices FAQ Java Exception Handling FAQ Java Synchronization FAQ Java Threads & Concurrency FAQ Java Collection Framework FAQ Java File I/O & Serialization FAQ Java Serialization & Deserialization FAQ Java Features FAQ Java Inner & Anonymous Classes FAQ Java Memory Management FAQ Java Packages FAQ Java Wrapper Classes FAQ Java Streams & Lambda FAQ

C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • Conditional Statements
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • Loops Statements
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processing
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.