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                                                                                                                            

Learn C Programming Language Tutorials

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

Static Keyword Types

Now that you know what is static variable in C, let’s explore the types that you can use in different situations:

Global Static Variable

When a global variable is declared with the static keyword, it is called static. It is introduced at the beginning of the program and is visible throughout.

Local Static Variable

A local variable is referred to as static when it is declared with the static keyword. Static local variables have the same visibility scope as automatic local variables, but their memory is valid throughout the program. That being said, if the function alters the static local variable in the first function call, the updated value will likewise be accessible in the subsequent function calls.

Static Members Variables 

Static member variables are defined as those that are declared in a class using the static keyword. Instead of being exclusive to one instance, they are accessible to all class instances.

Static Method

Static methods are member functions of classes with the specified static keyword. It is not exclusive to any one instance of a class; rather, it is available to all of them.

Static Variable In C: Knowing The Properties

Only knowing what is a static variable in C isn’t enough to understand this programming concept. Here are the few major properties of static variable in C to increase your understanding:

  • Lifetime: During the full program execution, a static variable’s lifetime is undefined.
  • Local or Global Scope: These are two possible outcomes for a static variable. A variable is considered local if defined inside a function and global if declared outside of any function.
  • Memory Allocation: The program’s data segment, not the stack, is where a static variable’s memory is allocated.
  • Programming Execution: It only involves initializing a static variable once during program loading.
  • Default Initialization: Depending on the data type, a static variable’s initial value is either NULL or zero (0) if it is not explicitly set.

Static Variable In C: Knowing All The Uses

Static variables in C are frequently used for the following purposes:

  • Tracking Progress: Tracing the progress of a loop or measuring the number of times a function has been called are two examples of using static variables to store state information between function calls. Static variables do this by holding onto their values.
  • Data Caching for Frequent Access: In C, static variables can be utilized to hold data that is costly to process and frequently accessed, such as the contents of a file or the outcome of intricate calculations.
  • Data Sharing Across Related Functions: In C, data can be shared among related functions inside a file without being visible to other files using global static variables.
  • Putting Persistent Storage Into Practice: C’s static variables can be used to save data across program runs, enabling the application to pick up where it left off when it was shut down.
  • Enhancing Performance: Static variables can reduce the time and resources required to compute or operate by keeping their values across function calls.

Variables Other Than Static Variables in C Programming

In contrast, automatic variables—the default kind of variable in C—are different from the static variable in C programming. When a function is called, the program automatically generates automatic variables and deallocates memory when the function call is finished. We can also have external, volatile, register, and constant variables in addition to automated ones.

Here is a quick summary of these.

  • Register Variables: These are used to indicate to the compiler how to save a variable; they are often restricted to function scope. Nevertheless, they are optional, and the compiler may overlook them.
  • External Variables: Also referred to as global variables, they have file scope attributes and are defined outside of functions. While global variables cannot have function scope, they are comparable to static variables because they have file scope.
  • Volatile Variables: These are used to tell the compiler that a variable’s value could change without warning, possibly due to hardware interruptions. The compiler does not optimize these variables; rather, the values are read from memory.
  • Constant Variables: Once initialized, constant variables cannot be changed again; they are declared with the “const” keyword. As a result, their primary use is to declare constants that we wish to remain unchanged during runtime.

Advantages of Using Static Keyword in C

Programmers can benefit from using static keyword in C in several ways, such as:

  • Encapsulation: Static keywords and functions aid code encapsulation and naming conflict prevention by restricting their scope to the current file. 
  • Memory Management: Static keyword C# can be utilized to control memory more effectively by lowering the requirement for dynamic memory allocation because they remain valid for the duration of the application.
  • Performance: Since static keywords and functions are resolved at compile time rather than run time, they can improve performance.
  • Data Persistence: C# Static keywords help store persistent data that must be shared over several function calls since they hold their values between calls and functions.
  • Information Hiding: By separating implementation details from other sections of the code, static functions can simplify and improve the readability of the code.
  • Code Reusability: Reusable utility functions that can be applied across the codebase can be implemented using static functions.

In conclusion, there is plenty of scope of static variables in C that can enhance memory management, performance, code reuse, and code organization. They are an effective tool for C programmers since they can also be used to mask implementation details and provide data permanence.

Static Variable In C: Best Practices

It makes sense to go over how to use static variable in C language now that we’ve discussed their properties, types, and uses. We can limit the concurrent access of variables using synchronization techniques, which can help to reduce thread safety issues.

Mutex and atomic operations are the two most widely used techniques.

Mutual exclusion, or mutex, limits the number of threads accessing a given variable. The thread attempts to obtain a mutex lock, which they use. However, the software will pause the request if another thread is currently accessing this lock.

On the other hand, atomic operations don’t need locks. They ensure the program may execute an operation atomically—that is, without being interrupted by other threads. 

Common atomic operations are load-and-store, in which a value is loaded from memory and temporarily stored in a register. At the same time, the program updates the variable and read-modify-write, in which the program modifies the variable and overwrites its value. 

Using load-and-store in conjunction with other synchronization techniques, such as mutexes, is necessary because it lacks atomicity on its own.

How do you implement static variables in class C++?

A static variable in class C++ programming language is easy to implement. In this case, we must first declare a single function. It’ll be an easy function to use. We are going to designate one variable as static under that function. Before the variable is declared, we must leverage a static int in C. After that, we give it a value.

Right now, we’re adding 1 to the variable before printing it. We now need to declare a single loop in the main function. You can choose which loop to use for that. One while loop has been declared here. For a predetermined period of time, the loop calls the function. 

Normally, the function’s defined variable will output just the supplied value. However, it will print the numerical sequence in this instance because the variable is static. The variable’s increment functions in this case as though it is static.

Syntax: Static data-type variable-name;

Static Variables In C: How Do They Optimize Program Performance?

Program performance can be increased using static variables in C++, which lowers the time and memory requirements for program execution. The data segment is a dedicated memory area allocated during compile time to house static variables.

As a result, there is less cost involved in memory allocation and deallocation because they do not require dynamic allocation during runtime. Furthermore, frequently requested data can be stored in static variables, eliminating the need to recompile it each time the function is called because static variables maintain their values between function calls.

Similarly, the time required to invoke a static function decreases because it is resolved at compile time. Static functions allow the compiler to optimize the code more effectively, which leads to faster execution times because they are hidden from view outside of the file in which they are declared. 

Also, the compiler can carry out more aggressive optimizations, including inlining and loop unrolling, which further enhances efficiency because static functions cannot be invoked from outside the file. Using C’s static keywords and functions can result in quicker program execution times and more economical memory use. 

Mistakes/Errors To Avoid While Using Static Variables In C

  • Initialization: Programmers should ensure that the value of a static variable they manually initialize is independent of the program’s state during runtime since this initialization is only done once upon program loading. Static variables are automatically initialized to zero.
  • Naming conflicts: Since static variables in C can only be viewed within the same file, it is possible for static variables to have the same name across files accidentally. Programmers can prevent this issue by giving static variables unique names or by ensuring that the variable is only visible within the same file by using the static keyword in conjunction with external linkage.
  • Thread safety: Static variables can potentially cause issues in multi-threaded programs because they hold their values in between function calls. Concurrent access to the same static variable by several threads might result in race situations and other synchronization issues.

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