Programs

Learn About Static Variable in C [With Coding Example]

In your programming journey, you might have worked around most of the variables. They are a very important aspect for any programmer, as declaring a variable determines the size, layout, range of values stored in the memory, and the set of operations to be applied to it. It is the name given to a storage area that a program can manipulate. In this article, we will discuss one of the most important variables in C, i.e., the static variable.

Static keyword in C is used quite frequently. One thing that is often confused by most of the programmers is how local and global variables affect static. In each case, the static keyword works differently in terms of where the data is stored and how it behaves throughout the program. The following are the primary uses of a static keyword:

 i. A local variable in a function or static local variable: Visibility is the same as the automatic local variables.

ii. Global variable in a module or static global variable: Declared at the top of a program.

iii. A function in a module or static function: It exists throughout the program.

iv. Member variable or static member variable: Accessed by all the instances of a class.

v. A method or static method: Accessed by all the instances of a class.

We will look into all the three use cases and how they change with the storage area of the variable and enhance the quality of code.

Check out our free courses to get an edge over the competition.

What is a Static Variable?

In programming, a static variable is the one allocated “statically,” which means its lifetime is throughout the program run. It is declared with the ‘static’ keyword and persists its value across the function calls.

Syntax:

The syntax of a static variable is:

static data_type variable_name;

Check out upGrad’s Advanced Certification in Blockchain

Explore our Popular Software Engineering Courses

upGrad’s Exclusive Software and Tech Webinar for you –

SAAS Business – What is So Different?

 

Static Variable Declaration

When a static variable is declared, a copy of it is created. The main purpose these are used in place of a local variable is that they retain the value assigned in the scope where it is present. The programmer does not need to initialize the variable again and again in the new scope of a program. It exists throughout the entire program.

Static, in general, is a storage class specifier applied to any data type. It directs the compiler to limit a variable or function in the program scope and persists throughout the lifetime of the program. This property allows static to be encapsulated or hidden variables from the rest of the program preventing any unintended access. The developer can control how variables are accessed within a module. This is a good programming practice.

Check out upGrad: Full Stack Development Bootcamp (JS/MERN)

Learn Online Software Development Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs or Masters Programs to fast-track your career.

Read: Top 130+ Java Interview Questions & Answers

Static Variable in a Program

· A static variable remains in the memory space during the execution of the entire code.

· The default initialization value of a static variable is zero, even if it is not assigned, which is not the case in a local variable.

· It is mandatory to initialize the static variable using the static keyword in C else it will return an error.

· The static variable is only initialized the first time when a function is called.

· In a static variable, the memory of a static variable is allocated.

· A global static variable is not accessible outside the program. 

Explore Our Software Development Free Courses

Basic Program on Static Variable in C

#include <stdio.h>  

int main()

{

         printf(“%d”,func());

         printf(“\n%d”,func());

return 0;  

}  

int func()  

{  

                static int count=0;  

               count++;  

                return count;  

}  

Here in this code, the count variable is declared as a static variable. With every call of the func(), the value of count updates to 1. In the next function call, the count variable value becomes 2. Thus, the value of the static variable persists in the function call.

Output:

1                                                                                                                            

In-Demand Software Development Skills

Difference Between Local and Static Variable

Both local and static variables are used interchangeably in a program. Here are some key differences between the two:

Distinguishing Points Local Variable Static Variable
Variable Keyword Declaration 1. It is declared by an automatic variable, e.g., int a = 1. 1. It is declared by a static variable, e.g., static int a = 1.
Variable Declaration 2. It is declared inside the function. 2. It is declared either inside or outside the function.
Variable Creation 3. It is created every time a function is called. 3. It is created for the 1st function call only, and the same variable is used for further call.
Variable Initialisation 4. It is initialized every time a function is called. 4. It is initialized only once in a program.
Variable Default Value 5. If not initialized, a garbage value is stored in the variable. 5. If not initialized, the value 0 is stored in static by default.
Variable Termination 6.     When the function ends, it terminates. 6. If declared inside a function, it is accessible in that function only. The scope is limited to that function, and its lifetime is until the program terminates. If declared outside the function, the variable will be global and accessible by any function in the file. The scope is the file, but the lifetime is until the program terminates.

With this table, it is clear why static variables are preferred to local variables.

Code Comprising Both Local and Static Variable

#include <stdio.h>

int main() {

   auto int a = -15;

   static int b = 5;

   printf(“Value of the auto variable a is %d\n”, a);

   printf(“Value of the static variable b is %d\n”,b);

   if(a!=0)

   printf(“The sum of static and auto variable is %d\n”,(b+a));

   return 0;

}

Program Output:

Value of the auto variable is -15

Value of the static variable is 5

The sum of the static and auto variable is -10

Also Read: C Project Ideas

Read our Popular Articles related to Software Development

Summary

The static keyword is used widely for many features that it offers in C programming. Its main use is to limit the scope of variables defined in a function or module. Developers can experience security, as the variables and functions can be hidden from the external program through the use of the static variable. In many modern object-oriented languages, the use of static is replaced by private and public.

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.

What are the major statements used in SQL?

SELECT - takes data from one or more tables and selects it. FROM - indicates which table or tables will be used to select data. WHERE - provides the condition(s) under which data should be chosen. GROUP BY - organizes information based on one or more columns. HAVING - defines the condition(s) under which data should be grouped. ORDER BY - determines the order in which data is displayed.

What are the uses of explode function?

Creating tables, entering data, choosing data, updating data, and removing data are all major SQL functions. In PHP, the explode() method breaks a string into many strings. A string is broken into smaller pieces using this function. In addition, the function can be used to extract data from a string.

What are the skills required to become a PHP developer?

PHP is a server-side scripting language that is primarily used for web development but may also be used for other purposes. Rasmus Lerdorf came up with the idea in 1994. When the document is requested, PHP code is placed into the HTML content and evaluated by the webserver. Due to its simplicity of use and extensive feature set, PHP is a popular choice for web development. It's free, open-source software distributed under the PHP License. A PHP developer is a programmer who creates websites and web applications using the PHP programming language. PHP developers must have strong problem-solving abilities, as they are frequently called upon to debug code and locate and correct issues. Because PHP is a programming language, they must also have good programming skills. They must be able to communicate successfully with other members of the development team, as well as clients.

Want to share this article?

Prepare for a Career of the Future

INDUSTRY TRUSTED LEARNING - INDUSTRY-RECOGNIZED CERTIFICATION.
Enroll Today

Leave a comment

Your email address will not be published. Required fields are marked *

Our Popular Software Engineering Courses

Get Free Consultation

Leave a comment

Your email address will not be published. Required fields are marked *

×
Get Free career counselling from upGrad experts!
Book a session with an industry professional today!
No Thanks
Let's do it
Get Free career counselling from upGrad experts!
Book a Session with an industry professional today!
Let's do it
No Thanks