- Blog Categories
- Software Development Projects and Ideas
- 12 Computer Science Project Ideas
- 28 Beginner Software Projects
- Top 10 Engineering Project Ideas
- Top 10 Easy Final Year Projects
- Top 10 Mini Projects for Engineers
- 25 Best Django Project Ideas
- Top 20 MERN Stack Project Ideas
- Top 12 Real Time Projects
- Top 6 Major CSE Projects
- 12 Robotics Projects for All Levels
- Java Programming Concepts
- Abstract Class in Java and Methods
- Constructor Overloading in Java
- StringBuffer vs StringBuilder
- Java Identifiers: Syntax & Examples
- Types of Variables in Java Explained
- Composition in Java: Examples
- Append in Java: Implementation
- Loose Coupling vs Tight Coupling
- Integrity Constraints in DBMS
- Different Types of Operators Explained
- Career and Interview Preparation in IT
- Top 14 IT Courses for Jobs
- Top 20 Highest Paying Languages
- 23 Top CS Interview Q&A
- Best IT Jobs without Coding
- Software Engineer Salary in India
- 44 Agile Methodology Interview Q&A
- 10 Software Engineering Challenges
- Top 15 Tech's Daily Life Impact
- 10 Best Backends for React
- Cloud Computing Reference Models
- Web Development and Security
- Find Installed NPM Version
- Install Specific NPM Package Version
- Make API Calls in Angular
- Install Bootstrap in Angular
- Use Axios in React: Guide
- StrictMode in React: Usage
- 75 Cyber Security Research Topics
- Top 7 Languages for Ethical Hacking
- Top 20 Docker Commands
- Advantages of OOP
- Data Science Projects and Applications
- 42 Python Project Ideas for Beginners
- 13 Data Science Project Ideas
- 13 Data Structure Project Ideas
- 12 Real-World Python Applications
- Python Banking Project
- Data Science Course Eligibility
- Association Rule Mining Overview
- Cluster Analysis in Data Mining
- Classification in Data Mining
- KDD Process in Data Mining
- Data Structures and Algorithms
- Binary Tree Types Explained
- Binary Search Algorithm
- Sorting in Data Structure
- Binary Tree in Data Structure
- Binary Tree vs Binary Search Tree
- Recursion in Data Structure
- Data Structure Search Methods: Explained
- Binary Tree Interview Q&A
- Linear vs Binary Search
- Priority Queue Overview
- Python Programming and Tools
- Top 30 Python Pattern Programs
- List vs Tuple
- Python Free Online Course
- Method Overriding in Python
- Top 21 Python Developer Skills
- Reverse a Number in Python
- Switch Case Functions in Python
- Info Retrieval System Overview
- Reverse a Number in Python
- Real-World Python Applications
- Data Science Careers and Comparisons
- Data Analyst Salary in India
- Data Scientist Salary in India
- Free Excel Certification Course
- Actuary Salary in India
- Data Analyst Interview Guide
- Pandas Interview Guide
- Tableau Filters Explained
- Data Mining Techniques Overview
- Data Analytics Lifecycle Phases
- Data Science Vs Analytics Comparison
- Artificial Intelligence and Machine Learning Projects
- Exciting IoT Project Ideas
- 16 Exciting AI Project Ideas
- 45+ Interesting ML Project Ideas
- Exciting Deep Learning Projects
- 12 Intriguing Linear Regression Projects
- 13 Neural Network Projects
- 5 Exciting Image Processing Projects
- Top 8 Thrilling AWS Projects
- 12 Engaging AI Projects in Python
- NLP Projects for Beginners
- Concepts and Algorithms in AIML
- Basic CNN Architecture Explained
- 6 Types of Regression Models
- Data Preprocessing Steps
- Bagging vs Boosting in ML
- Multinomial Naive Bayes Overview
- Gini Index for Decision Trees
- Bayesian Network Example
- Bayes Theorem Guide
- Top 10 Dimensionality Reduction Techniques
- Neural Network Step-by-Step Guide
- Technical Guides and Comparisons
- Make a Chatbot in Python
- Compute Square Roots in Python
- Permutation vs Combination
- Image Segmentation Techniques
- Generative AI vs Traditional AI
- AI vs Human Intelligence
- Random Forest vs Decision Tree
- Neural Network Overview
- Perceptron Learning Algorithm
- Selection Sort Algorithm
- Career and Practical Applications in AIML
- AI Salary in India Overview
- Biological Neural Network Basics
- Top 10 AI Challenges
- Production System in AI
- Top 8 Raspberry Pi Alternatives
- Top 8 Open Source Projects
- 14 Raspberry Pi Project Ideas
- 15 MATLAB Project Ideas
- Top 10 Python NLP Libraries
- Naive Bayes Explained
- Digital Marketing Projects and Strategies
- 10 Best Digital Marketing Projects
- 17 Fun Social Media Projects
- Top 6 SEO Project Ideas
- Digital Marketing Case Studies
- Coca-Cola Marketing Strategy
- Nestle Marketing Strategy Analysis
- Zomato Marketing Strategy
- Monetize Instagram Guide
- Become a Successful Instagram Influencer
- 8 Best Lead Generation Techniques
- Digital Marketing Careers and Salaries
- Digital Marketing Salary in India
- Top 10 Highest Paying Marketing Jobs
- Highest Paying Digital Marketing Jobs
- SEO Salary in India
- Brand Manager Salary in India
- Content Writer Salary Guide
- Digital Marketing Executive Roles
- Career in Digital Marketing Guide
- Future of Digital Marketing
- MBA in Digital Marketing Overview
- Digital Marketing Techniques and Channels
- 9 Types of Digital Marketing Channels
- Top 10 Benefits of Marketing Branding
- 100 Best YouTube Channel Ideas
- YouTube Earnings in India
- 7 Reasons to Study Digital Marketing
- Top 10 Digital Marketing Objectives
- 10 Best Digital Marketing Blogs
- Top 5 Industries Using Digital Marketing
- Growth of Digital Marketing in India
- Top Career Options in Marketing
- Interview Preparation and Skills
- 73 Google Analytics Interview Q&A
- 56 Social Media Marketing Q&A
- 78 Google AdWords Interview Q&A
- Top 133 SEO Interview Q&A
- 27+ Digital Marketing Q&A
- Digital Marketing Free Course
- Top 9 Skills for PPC Analysts
- Movies with Successful Social Media Campaigns
- Marketing Communication Steps
- Top 10 Reasons to Be an Affiliate Marketer
- Career Options and Paths
- Top 25 Highest Paying Jobs India
- Top 25 Highest Paying Jobs World
- Top 10 Highest Paid Commerce Job
- Career Options After 12th Arts
- Top 7 Commerce Courses Without Maths
- Top 7 Career Options After PCB
- Best Career Options for Commerce
- Career Options After 12th CS
- Top 10 Career Options After 10th
- 8 Best Career Options After BA
- Projects and Academic Pursuits
- 17 Exciting Final Year Projects
- Top 12 Commerce Project Topics
- Top 13 BCA Project Ideas
- Career Options After 12th Science
- Top 15 CS Jobs in India
- 12 Best Career Options After M.Com
- 9 Best Career Options After B.Sc
- 7 Best Career Options After BCA
- 22 Best Career Options After MCA
- 16 Top Career Options After CE
- Courses and Certifications
- 10 Best Job-Oriented Courses
- Best Online Computer Courses
- Top 15 Trending Online Courses
- Top 19 High Salary Certificate Courses
- 21 Best Programming Courses for Jobs
- What is SGPA? Convert to CGPA
- GPA to Percentage Calculator
- Highest Salary Engineering Stream
- 15 Top Career Options After Engineering
- 6 Top Career Options After BBA
- Job Market and Interview Preparation
- Why Should You Be Hired: 5 Answers
- Top 10 Future Career Options
- Top 15 Highest Paid IT Jobs India
- 5 Common Guesstimate Interview Q&A
- Average CEO Salary: Top Paid CEOs
- Career Options in Political Science
- Top 15 Highest Paying Non-IT Jobs
- Cover Letter Examples for Jobs
- Top 5 Highest Paying Freelance Jobs
- Top 10 Highest Paying Companies India
- Career Options and Paths After MBA
- 20 Best Careers After B.Com
- Career Options After MBA Marketing
- Top 14 Careers After MBA In HR
- Top 10 Highest Paying HR Jobs India
- How to Become an Investment Banker
- Career Options After MBA - High Paying
- Scope of MBA in Operations Management
- Best MBA for Working Professionals India
- MBA After BA - Is It Right For You?
- Best Online MBA Courses India
- MBA Project Ideas and Topics
- 11 Exciting MBA HR Project Ideas
- Top 15 MBA Project Ideas
- 18 Exciting MBA Marketing Projects
- MBA Project Ideas: Consumer Behavior
- What is Brand Management?
- What is Holistic Marketing?
- What is Green Marketing?
- Intro to Organizational Behavior Model
- Tech Skills Every MBA Should Learn
- Most Demanding Short Term Courses MBA
- MBA Salary, Resume, and Skills
- MBA Salary in India
- HR Salary in India
- Investment Banker Salary India
- MBA Resume Samples
- Sample SOP for MBA
- Sample SOP for Internship
- 7 Ways MBA Helps Your Career
- Must-have Skills in Sales Career
- 8 Skills MBA Helps You Improve
- Top 20+ SAP FICO Interview Q&A
- MBA Specializations and Comparative Guides
- Why MBA After B.Tech? 5 Reasons
- How to Answer 'Why MBA After Engineering?'
- Why MBA in Finance
- MBA After BSc: 10 Reasons
- Which MBA Specialization to choose?
- Top 10 MBA Specializations
- MBA vs Masters: Which to Choose?
- Benefits of MBA After CA
- 5 Steps to Management Consultant
- 37 Must-Read HR Interview Q&A
- Fundamentals and Theories of Management
- What is Management? Objectives & Functions
- Nature and Scope of Management
- Decision Making in Management
- Management Process: Definition & Functions
- Importance of Management
- What are Motivation Theories?
- Tools of Financial Statement Analysis
- Negotiation Skills: Definition & Benefits
- Career Development in HRM
- Top 20 Must-Have HRM Policies
- Project and Supply Chain Management
- Top 20 Project Management Case Studies
- 10 Innovative Supply Chain Projects
- Latest Management Project Topics
- 10 Project Management Project Ideas
- 6 Types of Supply Chain Models
- Top 10 Advantages of SCM
- Top 10 Supply Chain Books
- What is Project Description?
- Top 10 Project Management Companies
- Best Project Management Courses Online
- Salaries and Career Paths in Management
- Project Manager Salary in India
- Average Product Manager Salary India
- Supply Chain Management Salary India
- Salary After BBA in India
- PGDM Salary in India
- Top 7 Career Options in Management
- CSPO Certification Cost
- Why Choose Product Management?
- Product Management in Pharma
- Product Design in Operations Management
- Industry-Specific Management and Case Studies
- Amazon Business Case Study
- Service Delivery Manager Job
- Product Management Examples
- Product Management in Automobiles
- Product Management in Banking
- Sample SOP for Business Management
- Video Game Design Components
- Top 5 Business Courses India
- Free Management Online Course
- SCM Interview Q&A
- Fundamentals and Types of Law
- Acceptance in Contract Law
- Offer in Contract Law
- 9 Types of Evidence
- Types of Law in India
- Introduction to Contract Law
- Negotiable Instrument Act
- Corporate Tax Basics
- Intellectual Property Law
- Workmen Compensation Explained
- Lawyer vs Advocate Difference
- Law Education and Courses
- LLM Subjects & Syllabus
- Corporate Law Subjects
- LLM Course Duration
- Top 10 Online LLM Courses
- Online LLM Degree
- Step-by-Step Guide to Studying Law
- Top 5 Law Books to Read
- Why Legal Studies?
- Pursuing a Career in Law
- How to Become Lawyer in India
- Career Options and Salaries in Law
- Career Options in Law India
- Corporate Lawyer Salary India
- How To Become a Corporate Lawyer
- Career in Law: Starting, Salary
- Career Opportunities: Corporate Law
- Business Lawyer: Role & Salary Info
- Average Lawyer Salary India
- Top Career Options for Lawyers
- Types of Lawyers in India
- Steps to Become SC Lawyer in India
- Tutorials
- C Tutorials
- Recursion in C: Fibonacci Series
- Checking String Palindromes in C
- Prime Number Program in C
- Implementing Square Root in C
- Matrix Multiplication in C
- Understanding Double Data Type
- Factorial of a Number in C
- Structure of a C Program
- Building a Calculator Program in C
- Compiling C Programs on Linux
- Java Tutorials
- Handling String Input in Java
- Determining Even and Odd Numbers
- Prime Number Checker
- Sorting a String
- User-Defined Exceptions
- Understanding the Thread Life Cycle
- Swapping Two Numbers
- Using Final Classes
- Area of a Triangle
- Skills
- Software Engineering
- JavaScript
- Data Structure
- React.js
- Core Java
- Node.js
- Blockchain
- SQL
- Full stack development
- Devops
- NFT
- BigData
- Cyber Security
- Cloud Computing
- Database Design with MySQL
- Cryptocurrency
- Python
- Digital Marketings
- Advertising
- Influencer Marketing
- Search Engine Optimization
- Performance Marketing
- Search Engine Marketing
- Email Marketing
- Content Marketing
- Social Media Marketing
- Display Advertising
- Marketing Analytics
- Web Analytics
- Affiliate Marketing
- MBA
- MBA in Finance
- MBA in HR
- MBA in Marketing
- MBA in Business Analytics
- MBA in Operations Management
- MBA in International Business
- MBA in Information Technology
- MBA in Healthcare Management
- MBA In General Management
- MBA in Agriculture
- MBA in Supply Chain Management
- MBA in Entrepreneurship
- MBA in Project Management
- Management Program
- Consumer Behaviour
- Supply Chain Management
- Financial Analytics
- Introduction to Fintech
- Introduction to HR Analytics
- Fundamentals of Communication
- Art of Effective Communication
- Introduction to Research Methodology
- Mastering Sales Technique
- Business Communication
- Fundamentals of Journalism
- Economics Masterclass
- Free Courses
Storage Classes in C: Different Types of Storage Classes [With Examples]
Updated on 25 January, 2024
108.4K+ views
• 17 min read
Table of Contents
Coding with C is highly centered upon using variables in every program. Those are the key aspects of C programming. Every variable in C has two properties; type and storage classes. Among them, the type refers to the data type of the variable, and storage classes in C determine the scope, lifetime, and visibility of the variable. Storage classes in C are used to find the lifetime, visibility, memory location, and initial value of a variable.
With that in mind, let us delve into storage class and the types of storage classes in C.
In this blog post, we will have a detailed look at the storage classes in C, its types, and how its characteristics influence the output of the program with some programming examples.
Storage Classes In C With Examples Of Use
Any storage class actually is representative of visibility and location of any variable. This tells users what portion of a code is accessible as a variable. Storage class for C can help describe the following things:
- A variable scope: Storage classes in C are widely used to determine the lifetime, visibility, or scope of existing variables and functions. These classes in C precede the modifying type of variables.
- Location for variable storage: While creating variables in C, it is assigned a specific memory address, referred to as the location of its storage in the system. Once a variable is given a value, this is the memory address it is stored in.
- Initialized value for variable: Once a variable is declared, it needs to be initialized first. Variable initialization is of two types: explicit and implicit. Explicitly initialized variables are ones that are given a value in the declaration statement, whereas when variables are given a value while processing, they are implicitly initialized.
- Variable lifetime: The amount of time a variable takes up a valid space in a computer’s storage is known as variable lifetime. It is also defined as the period between when a memory is assigned to hold one variable till the time it is freed. When the allocated variable is freed from the scope, its lifetime ends.
- Users accessing a variable: Refers to users or parts of a program that can access the variable. These can involve ‘extern’ variables, which one can define out of any function block, or ‘global’ variables, which one can define outside the scope of every existing variable.
Overall, a storage class stands representative of information about any variable. This is the best way to explain storage classes in c with examples.
Also, Check out our free courses
Learn to build applications like Swiggy, Quora, IMDB and more
What Are Storage Classes In C?
Before delving into the various types, let us first address the question: What is a storage class in C?
Storage classes in C allocate the storage area of a variable that will be retained in the memory. They are stored in the RAM of a system. Apart from the storage space, they determine the scope of a variable. Variables in the C program are stored in a physical location in the random memory, which is mainly the device’s memory and CPU registers.
Storage classes in C also define the lifetime of the variable and term it as ‘local’ or ‘global’. Storage classes are also useful to define the scope or visibility, and the initial value of the variable. There are primarily four storage classes in C, viz. automatic, register, static, and external. We will discuss each one by one further.
Check out upGrad’s Full Stack Development Bootcamp
Get Software Development Course from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.
How Storage Classes In C Are declared?
Storage classes in C define the scope, visibility, and lifetime of variables within a program.
The four storage classes in C are declared in a block or program with the storage class specifiers, auto, register, extern, static. There is one more storage class specifier, ‘typedef’ used in the syntactic form, and does not reserve storage. The specifiers instruct the compiler on storing the variables. The external storage class in C tell the compiler that variable defined is declared with external linkage.
These are also referred to as the four primary storage class specifiers in C. Here is a detailed explanation of the four:
- auto: Variables declared with the auto storage class in C are automatically created within a code block (usually within a function) and are destroyed when the block exits. This storage class is default for all local variables in C, so explicitly using “auto” is optional.
- register: The “register” storage class is used to suggest to the compiler that a variable be stored in a CPU register for faster access. However, it’s merely a suggestion, and the compiler might or might not comply. Like “auto” variables, “register” variables have block scope.
- static: Variables with the “static” storage class persist throughout the program’s execution. A static variable retains its value between function calls when declared inside a function. If declared outside a function, it becomes accessible only within the file where it’s declared, acting as a file-local variable.
- extern: The “extern” storage class is used to declare variables or functions defined in other files. It’s used to access global variables or functions defined in a separate file from where they’re being used. When used to declare a variable, it refers to a global variable defined elsewhere.
Difference Between Definition and Declaration of Storage Class in C
There is a key difference between defining and declaring a variable. Defining a variable is about allocating the memory for the variable and declaring it means initializing it with a value.
Declaring Storage Classes in C:
When the existence and properties of a variable, function, or identifier are announced to the compiler, it is called a declaration. It helps provide necessary information about the entity without allocating memory or specifying its value.
Declaration of storage classes in C might involve specifying the storage class of a variable with keywords like “static”, “extern”, “register”, and “auto.” This helps outline the variable’s characteristics, including scope, lifetime, and accessibility, without assigning memory or initializing its value.
Defining Storage Classes in C:
Definition involves providing the actual implementation or instantiation of the declared entity. For variables, it includes allocating memory, assigning an initial value, and specifying the characteristics declared earlier.
Defining a variable with a specific storage class involves assigning it memory as per the rules of the storage class and initializing its value if required. This is where the actual storage space for the variable is set aside based on its scope, lifetime, and other properties specified in the declaration.
Table of Key Differences
Parameters | Defining a storage class | Declaring a storage class |
Purpose | Declarations announce the existence and properties of an entity | Definitions provide the implementation or instantiation |
Memory Allocation and Initialization | Declarations do not allocate memory or initialize values | Definitions involve allocating memory and specifying initial values for variables |
Usage in Code | Declarations typically appear in header files or at the beginning of functions to inform the compiler about the characteristics of entities | Definitions are where memory is allocated and values are set, usually seen in the global scope or within functions |
There is a key difference between defining and declaring a variable. Defining a variable is about allocating the memory for the variable and declaring it means initializing it with a value.
Check out Java Bootcamp from upGrad
Syntax:
storage_class_specifier data_type variable_name;
Read: Interesting Project Ideas & Topics in C# For Beginners
Special Case: When no storage class specifier is declared or defined in a program
There is at least one storage class specifier is given in the variable declaration. But, in case, there is no storage class specifier specified, the following rules are followed:
1. Variables declared within a function are considered as auto.
Local variables are defined with the help of an automatic/auto storage class. Unless explicitly specified, a variable in auto storage class is allocated by default.
An auto variable’s scope is limited only to a specific block. The access gets eliminated once the block loses control of the variable. Hence, only the block containing the declared auto variable can access it.
2. Functions declared within a function are considered as an extern.
Extern is a storage class stating that a variable is defined outside and not inside the same block where it has been used. An external linkage occurs when the value assigned to the variable is in a different block and can also be overwritten or changed in a separate block. Extern variables are basically global variables that are initialized with legal values at the location where they are declared for use elsewhere.
Normal global variables can be extern variables too. This can be achieved by placing the keyword ‘extern’ before declaring or defining it in any function or block.
3. Variables and functions declared outside a function are considered static, with external linkage.
Despite being static, these variables and functions still have external linkage. External linkage means that they can be accessed by other parts of the program if they use the extern keyword to reference them. This enables other files in the program to access and use these variables or functions by explicitly stating their existence with the extern keyword.
When variables or functions are declared outside any function without an explicit storage class specifier, they are automatically treated as static (limited in visibility to the file in which they are declared) while still maintaining the ability for external parts of the program to access them by specifying extern.
upGrad’s Exclusive Software and Tech Webinar for you –
SAAS Business – What is So Different?
What are the Types of Storage Classes in C?
In C programming, storage classes play a crucial role in determining the scope, visibility, and lifetime of variables. There are many types of storage classes in C, with each class having a distinct characteristic that governs how variables are stored, accessed, and managed within a program.
There are four storage classes in C, let’s have a look at them:
1. Automatic Storage Classes in C
Every variable defined in a function or block belongs to automatic storage class by default if there is no storage class mentioned. The variables of a function or block belong to the automatic storage class are declared with the auto specifier. Variables under auto in C are local to the block where they are defined and get discarded outside the block.
The automatic storage class in C is implicit to the C programming language, and explicitly using the auto specifier is optional. Despite this, explicitly specifying auto for variables within a function or block reinforces their automatic storage behavior. This makes it clearer in the code but redundant due to the default behavior of local variables in C.
A Simple Program Showing Automatic Storage Classes:
#include <stdio.h>
int main( )
{
auto int i = 11;
{
auto int i = 22;
{
auto int i = 33;
printf ( “%d “, i);
}
printf ( “%d “, i);
}
printf( “%d”, i);
}
The output of the Program:
3 2 1
Explanation:
In the above program, there is three times the variable i is declared. Variables with the same name can be defined in different blocks. Thus, this program will compile and execute successfully without any error. The function ‘printf’ in the innermost block will print 3 and the variable i in this block will be destroyed after the block ends.
The next one, the second outer block prints 2 which is then succeeded by the outer block which prints 1. The automatic variables are initialized properly; else you will get undefined values as the compiler does not give them an initial value.
Explore our Popular Software Engineering Courses
2. Register Storage Classes in C
The variables belonging to a register storage class are equivalent to auto in C but are stored in CPU registers and not in the memory, hence the name. They are the ones accessed frequently. The register specifier is used to declare the variable of the register storage class. Variables of a register storage class are local to the block where they are defined and destroyed when the block ends.
A Simple Program Showing Register Storage Classes:
#include <stdio.h>
int main()
{
register int i = 10;
int *p = &i; //error: address of register variable requested
printf(“Value of i: %d”, *p);
printf(“Address of i: %u”, p);
}
Explanation:
In the above program, the code tries to get the address of variable i into the pointer variable p but as i is declared as a register variable, the code won’t compile and will display the error ” Error: address of register variable requested”.
Only certain types of variables are placed into registers. Register variables are not given an initial value by the compiler.
Learn: C++ Vs Java: Difference Between C++ & Java
3. Static Storage Classes in C
The visibility of static variables is zero outside their function or file, but their values are maintained between calls. The variables with static storage class are declared with the static specifier. Static variables are within a function or file. The static specifier works differently with local and global variables.
A static storage class will instruct a compiler for keeping the local variable existing during the span of a program in place of creating and then destroying the same every time the scope arises around it. Thus, making all local variables static will allow the maintenance of the values between all function calls.
A static modifier gets applied to all global variables. Once done, this causes that particular variable scope restriction to a file where the same is declared.
The static specifier in programming works differently with both local and global variables. Take a look below to understand the static storage class in c.
Simple Programs Showing Static Storage Classes with Local and Global Variables:
i. Local Variable
#include <stdio.h>
void staticDemo()
{
static int i;
{
static int i = 1;
printf(“%d “, i);
i++;
}
printf(“%d”, i);
i++;
}
int main()
{
staticDemo();
staticDemo();
}
The output of the Program:
1 0
2 1
Explanation:
When a local variable is defined by a static specifier, inside a function or block, permanent storage space is created in the compiler. The static local variable is visible to the function or block where it is specified and retains its value between the function calls. In the above program, the static variable i is defined at two places in two blocks inside the staticDemo()function. staticDemo() is called two in the main function. In the next call, the static variables retain their old values and need not be initialized again.
ii. Global Variable
#include <stdio.h>
static int gInt = 1;
static void staticDemo()
{
static int i;
printf(“%d “, i);
i++;
printf(“%d”, globalInt);
globalInt++;
}
int main()
{
staticDemo();
staticDemo();
}
The output of the Program:
0 1
1 2
Explanation:
Static variables need to be initialized only once in a program and they are retained throughout the lifetime. They have a default initial value of zero.
When a global variable or function is defined by a static specifier, then that variable or function is known only to the file in which it is defined. For a global variable, other file routines cannot access and alter its contents as a static global variable has internal linkage. In the above program, the static global variable globalInt and a static function staticDemo(), are defined as static and they cannot be used outside the C file.
In-Demand Software Development Skills
4. External Storage Classes in C
External storage class variables or functions are declared by the ‘extern’ specifier. When a variable is declared with extern specifier, no storage is allotted to the variable and it is assumed that it has been already defined elsewhere in the program. With an extern specifier, the variable is not initialized. The reason why extern is used to specify a variable in a program to declare it with external linkage.
A Simple Program Showing External Storage Classes:
#include <stdio.h>
extern int i;
int main()
{
printf(“i: %d”, i);
}
int i = 1;
Explanation:
In the above C program, if extern int i is removed, there will be an error “Undeclared identifier ‘i’ because the variable i is defined after being used in printf. The extern specifier instructs the compiler that variable i has been defined and is declared here.
If you change extern int i; to extern int i = 5; you will get an error “Redefinition of ‘i'” because the extern specifier does not initialize a variable.
Read our Popular Articles related to Software
A Quick Summary Of Various Storage Classes In C
Let us take a quick look at summing up the basic information about various storage classes in c.
- Any storage class in C can be used for representing any additional information about any variable.
- Storage class stands for the scope as well as the lifespan of the variable.
- Storage class also tells clearly who can access any variable and from what place.
- The four different storage classes in C program are auto, register, extern, and static.
- Storage class specifier for C language can be used for defining variables or functions as well as parameters.
- Auto can be used for any local variable that is defined within the block or function.
- Register gets used for storing a variable in the CPU registers instead of a memory location for ease of access.
- Static gets usage for global as well as local variables. Both have their use cases within the C program.
- Extern can be used for data sharing between multiple C files.
Advantages and disadvantages of C Storage Class
Let’s look at the advantages of The C Storage Class:
- Helps to determine the scope, visibility, lifetime of a variable.
Storage classes help define the scope of variables, indicating where in the program they can be accessed. They also control the visibility of variables, determining whether they can be accessed from other parts of the program or limited to specific functions or files.
- We can use more than one variable with the same name.
An advantage of storage classes in C is the ability to use identical variable names in different scopes without conflicts. This feature enhances code organization and readability by allowing distinct variables with the same name in separate scopes, streamlining maintenance, and facilitating localized operations without affecting other variables.
- Helps in Memory Optimization:
Certain storage classes, such as the register storage class, offer memory optimization by suggesting to the compiler that frequently used variables be stored in CPU registers. This optimization enhances access speed for critical variables, potentially boosting program performance, especially in scenarios where rapid data access is crucial.
Some disadvantages of The C Storage Class:
- We cannot use more than one storage class for a single variable.
One limitation of storage class in C is the inability to use multiple storage classes for a single variable. Each variable in C can only have one storage class specified. This constraint can be limiting when attempting to modify or adapt existing code, especially when a variable’s usage requires different storage class characteristics in different parts of the program.
- Changing the program to meet different needs becomes difficult, as we have to keep in mind the scope and lifetime of the variable.
The fixed scope and lifetime defined by a specific storage class in C present challenges when adapting or extending code. Modifying the program to meet new requirements becomes intricate due to the predefined scope and lifetime of variables tied to their storage classes. This inflexibility complicates efforts to accommodate changing needs or incorporate new features, requiring meticulous management of variable declarations and storage classes.
Explore Our Software Development Free Courses
Final Words
Programming in C has garnered popularity in coding due to its versatility which allows programmers to use it in a myriad of applications, programs, and technologies. It is the backbone of operating systems and more complex-level software and is critical to programming languages and the software industry at large. As a foundational language, it is widely used for its simple and flexible nature, and its ability to function independently in machines.
This article details the concept of storage classes in C and tells you how its types differ from each other. When to use a particular storage class depends on the assignment and the scope, lifetime, and visibility of the variable you are dealing with.
If you are interested to learn more and need mentorship from industry experts, check out upGrad & IIIT Banglore’s PG Diploma in Full-Stack Software Development.
Frequently Asked Questions (FAQs)
1. What is the difference between an Array and a Stack?
Storing and organising data is necessary so that data can be accessed easily when required. Stack and Array are the two most common ways to store data. A Stack is a data structure represented by a sequential collection of elements in a fixed order. On the other hand, the Array is a collection of data values called elements, each of which is identified by an indexed array. A Stack can be implemented using an Array, while an Array cannot be implemented using a Stack.
2. What is the difference between Structure and Union?
The C programming language has many built-in data types. Users can create their own custom data types in 5 ways: bit-field, structure, union, typedef, and enumeration. Structure and Union are both user-defined data types. A structure is a user-defined, custom data type in C language which allows combining data items of different types under a single unit. A union is a data type that allows storing different data types in the same memory location. Several members can initialise at once in a structure, while only the first union member can be initialised. The keyword `struct’ is used to define a structure, while the keyword `union’ is used to define a union. Also, altering the value of one member in a structure will not affect the members of other structures. On the contrary, altering the value of a member of the Union will alter other members' values.
3. Which storage class helps in faster execution?
Storage classes are used to determine any given variable's memory, location, initial value, and visibility. Storage classes allocate the storage area of a variable to be retained in the memory. Although there are 5 different types of storage classes in C, the register storage class helps in faster execution. Register has more immediate access as the variables are stored in CPU registers rather than the RAM. The variables declared using register storage have no default value and are usually declared in the beginning of the program.
RELATED PROGRAMS