Introduction to the Static Modifier in C
This tutorial walks through a practical C project to understand how the static keyword affects variable behaviour and scope. Using an example involving an increment function defined across multiple files, it highlights differences between automatic, global, and static variables. To build foundational knowledge before diving deeper, consider reading Understanding Variables in C Programming: Declaration, Initialization, and Usage.
Setting Up the Increment Function Project
- Created a C console application project named
my-project1. - Defined the
increment()function in a separate source file (add.c). - The function initializes a local integer variable
countto 0, increments it by 1, and returns the value. - The
main()function callsincrement()three times, expecting cumulative increments.
Observing Unexpected Behaviour with Automatic Variables
- Each call to
increment()reinitializescountto 0. - Since
countis a local automatic variable, it is destroyed after function exits. - Every call returns 1 instead of incremental values.
- This behaviour showcases automatic variables' lifecycle limited to the function scope. For more on variable scopes, see Understanding Variable Scope: Local vs Global Variables in Programming.
Using Global Variables to Retain State
- Declared
countas a global variable outside any function. - Global variables are automatically initialized to 0 and retain value across function calls.
- Rewriting
increment()to use this globalcountresults in correct cumulative increment values (outputs 3).
Disadvantage of Global Variables
- Global variables are accessible and modifiable from any file within the project.
- Example showed
main.cmanipulating the globalcount, increasing it further. - This unrestricted access can lead to unintended side-effects or bugs.
Encapsulating with Static Global Variables
- Added the
statickeyword to the global variable declaration (e.g.,static int count;). - Static global variables are accessible only within the file they are declared.
- Attempting to access them externally with
externresults in compilation errors. - This restricts unwanted access while retaining cumulative value.
Static Local Variables to Maintain State Locally
- Declared
countas astatic intinsideincrement()function. - Static local variables:
- Are initialized only once (default to 0).
- Retain their value between function calls.
- Are accessible only within the function scope.
- Demonstrated correct cumulative increment output while limiting scope.
Important Rules and Best Practices
- Static variables must be initialized with constant literals, not variables or function return values.
- Static variables declared inside functions persist for the program lifetime but retain function-level scope.
- Use static globals to prevent other files from accessing and modifying variables unintentionally.
- Static locals provide controlled state retention without polluting global namespace.
Summary Points
- Automatic variables live only during function execution and are reinitialized every call.
- Global variables retain state but are visible to the entire project.
staticglobal variables limit visibility to their file, improving encapsulation.staticlocal variables maintain their value between function calls while hiding from other functions.- Static variables must be assigned constant initial values.
This comprehensive example clarifies how the static keyword helps manage variable lifetime and scope effectively in C programming. For further exploration on related topics, you might find these articles helpful: Comprehensive Guide to Integer Data Types and Modifiers in C Programming and Understanding the Register Modifier in Memory Hierarchy. Understanding these concepts ensures safer, more maintainable code when working with variables across multiple functions and files.
Now we are going to have a discussion on static modifier. Now I am going to create a project.
Click on File New Project
choose Console Applications click on Go. Then click on next.
choose C then next. Choose a project title for your project
In my case, the project name is my-project1
as you can see over here. Click on next. Click on Finish.
And finally your project is created. Click on this plus button over here, choose the main.c file
I am going to change this code a little bit. After that I am going to write some piece of code.
What Am I going to do here is, I am going to call increment function three times in this code.
This function is available in some other file. So, I am going to create this
increment function in some other file by creating an empty file over here. Let's create an empty file,
click on Yes because it is asking you Do you want to add this
new file in the active project? I am going to click Yes. And suppose I choose the name
of this file as add.c . And click on save. Click on OK.
In this add.c file, I am going to create a function, increment.
Let's see how I am going to create this. Here you can see that I have created an increment function.
Inside this function, I have written some lines of codes. First line is nothing but
creating a variable of integer type and assigning it a value 0. Then I am incrementing this value
that means I am incrementing this value by 1 as I am going to do
count + 1 which is 0 + 1 and I am storing this value inside this variable only.
And then what I did is, I simply returned the value of count. And this value returned means,
as you can see over here, this function's return type is integer. I am going to return
an integer variable. This simply means that the code which is going to call this function
after performing some operations, it will return some value back to this function.
That is the purpose of a function you can say. We are going to have a lot of discussion on function later on
but right now, this is the one thing you need to know. When I call this function,
I simply transfer the control from this main function to this increment function
which might be available in some other file and inside this function
I perform certain kind of computation and then I simply return the the variable which contains some value.
And this return value is coming back to this particular functioncode. And this thing is going to get
replaced with that value. And it will get assigned to this value variable.
I did this three times over here, because what I want from this main function is that,
when I call this increment function, it will increment some value. As I initialized this variable to 0
it will get incremented to 1 and simply get returned back to this particular place,
and assign to the value itself. Then what I am going to do is that, I am going to call this function again.
And increment the previous value that I had already incremented that is 1.
When I increment that value,this becomes 2 and the value returned would be 2 in that case. And stored in value variable.
Then I am going to perform the same thing and this time the returned value would be 3.
And I am simply going to print this value. Let's see what happens when we try to print this value.
We are expecting the value to be 3 Let's see what is going to be our output. Now this is something which is
not expected right? The value I am getting is equal to 1 which is not all all expected.
I am expecting the value to be 3. But I am getting output as equal to 1.
But why am I getting this output? Let's try to understand the code first. When I called this increment function,
then my control transferred from this main function to this increment function.
That means, in other file add.c which is there inside this project only.
Right? When I call this increment function, inside I defined this function,
I have written a count variable, and assigned it a value equal to 0
because this variable is of integer type and I assigned it an integer value.
Then what i did is I simply incremented the value right? which means I did count+1
which is 0+1 which is equal to 1 only. And the result is getting stored in this same variable count.
After that I simply return the count which means my control will again transfer back to this
particular increment function over here. That is my calling procedure. This is my called procedure.
This is calling procedure. I am going to give you all the details about the functions
in later chapters. You just have to understand that how the flow will go on. Right?
So when I pass the value, this will be equal to 1 because, I return count which is now 1
after performing this operation. Now the value 1 is passed to this increment function
and finally this 1 is assigned to this variable value. Right? What happens when we call this function again?
When we call this function again, then you see that this variable is again created
and assigned with the value equal to 0. Now this is what we need to recall from the previous lessons.
That what is the meaning of automatic variable. This variable is local in
in this function right? What does it really mean? When the function completes its execution
as in the previous case, and when I call this function, this is what is called.
Completion of this function means that this variable is destroyed which contained the value equal to 1.
When I call back this function again, then variable is again created and assigned with the value 0 again
And if I try to increment this value , this 0 is getting incremented and not the previous 1.
Because that is lost. Variable is simply destroyed. So we wont be able to
retain that value. And in this case also, I will get 0 as a count value.
and when I increment this, it will become 1 and get assigned to count variable. And simply return count.
In this case also 1 is returned. And when I come back to this function value equal to 1 is assigned.
When I call this increment function once again, this is again created. As the previous count variable
was destroyed. When I increment the value, this would be just 0+1 again,
and the count value is again equal to 1. And when I return the count, this is equal to 1 only.
And I simply print the value as 1. That is what we are getting as an output 1. I want to retain the previous value right?
whenever I call the function again and again. The purpose of this main function
is to increment the value of the previous value every time. And simply print the value equal to 3
instead of 1. When ever I call this increment function I would be able to retain previous value
and not new value every time. So what i am going to do in this case. I am going to make a little
change to this code. What I am going to do is I am going to declare this variable
as global instead of local variable to this particular scope. Now as you can see,
I changed the code a little bit. I declared this variable global instead of local
to this function. Now what is the advantage you get from this variable? Let's see. But before that
You don't need to initialize it to 0. Because we know this thing, when we wont initialize any
value to this variable, then automatically it will be initialized to 0.
Now, what is the advantage you got from this. Let's try to build and run the code. You get value equal to 3 now.
This means I would be able to retain the value which was previously there. Right? Now what is happening in this code.
I had declared this variable as global variable. Right? Now this variable is available
to all the functions within this file as well as all the other files in this project.
Right? This is the meaning of global variable. So I simply use this
global variable inside this increment function and I simply increment the value by 1.
Which was previously 0 automatically, you know this thing. When I increment this value to 1,
and assign it to count variable once again then I simply return value of count to this place.
Now the value is equal to 1. Right? Now when I again call this
increment function, then this variable is not recreated. Right? Why is it so?
Because this variable is not with in the scope of ant function or any block which gets
destroyed after the completion of the function. Here the function is completed not the whole file is destroyed.
Due to this reason, I would be able to retain the value which was previously equal to 1
and simply increment the value and return it. In this case, the count will be equal to 1
and not equal to 0 because the variable is not recreated. Note down this thing.
Because this variable is global variable, and it was never destroyed. Because the function finishes its execution
and this variable is not a part of this function, therefore variable is not destroyed.
We would be able to retain the value. I simply increment the value by 1, which now becomes 2
and simply return the count here in this function and assign it to value variable.
You call this increment function once again, then again variable was not destroyed and I would be able to retain the value
and now, this time it will become 3. And I simply return the value 3 to this increment function.
And then it would be assigned to this value. When I print this, I got my output equal to 3.
This is the advantage you get from a global variable. But there is one disadvantage as well.
As we know this thing that this global variable is available not only to this file,
but to all the functions as well as all the files in this project. Right? Now we know this thing
that this global variable is not only available to this file but it is visible to all the other files
which are available in this project. That means, for main.c as well this particular variable count
is also visible. Now suppose I change this code a little bit and I am going to declare
an extern integer variable. By declaring a count variable as extern, I would be able to use this
variable over here right? What I am going to do is, I am going to simply use this variable,
and manipulate it a little bit. Here I increment the value by 3 Right?
Count value is simply after this function equal to 3, then I use this variable in this main function
and I increment this value by 3. And assign this value to this value. And simply print it.
Then what would be the output. It is equal to 6. Right ? Because up till this point this is 3.
When I increment it by 3, This will become 6 Now this is something which is not
a good practice to do. Because, this variable count is meant for this particular file only.
Right? Suppose there is one case where I don't want this count variable to be shared
among other files. Then in that case, this is not a good practice. Because this variable is visible
to all the other files as well. Now if I want to hide, I wont be able to do that.
Because this variable is visible to all the other files. Therefore, all the other files would be
able to access it. Simply increment them and make some changes to them.
Sometimes we don't want this thing. We simply want this variable to be there inside this file only.
Suppose we want this thing, that this variable should be visible within this particular file you can say.
And not outside of this file. Then in that case, we are simply putting a key word
in front of it which is called "static". By putting a static key word
in front of this variable, Now, if I try to access this variable, with the help of extern
in this main.c file, then I wont be able to do that. And it will produce an error.
"Undefined reference to count" Because now in this case, the count is not visible
outside of this scope. This is visible to this file only. You can still use it over here.
But you wont be able to call this variable with the help of extern keyword and simply
use it in other file because, now in this case, static is put in front of this variable.
You can say this is the main advantage of using static. Variable is still global but now,
this is global within this particular file only and not to other files. By default value initialized to this variable
like a global variable, is equal to 0 only. Support I comment this with the help of
Ctrl Shift +C you can use this command to make comments, and here also, I comment this out.
Then if I run the code, then this would produce the answer equal to 3.
which was there for the global variable as well Now there is one more advantage that you get from this static variable.
And the advantage is that, even though this variable is declared globally, and
I would be able to retain its value. But when I declare it as local to this particular function,
Then also I will be able to retain the value. And that is the advantage or you can say the biggest
advantage of using static key word in front of a variable. Let's see how can we do that.
Now, instead of declaring it as a global variable, I declared it as local to this particular function over here.
Here instead of integer count, now I am having static int count. And as we know this thing,
that when I place static key word in front of this variable, the value is automatically
initialized to 0. When I declare a local variable, like integer count, in that
case the value is initialized to garbage. Right? We know this thing. Automatic variables are initialized
with garbage values. in this case, the value initializes is equal to 0. Even though it is local to this function.
And if I try to execute this code, then what happens is that we would be able to retain the value
and produce the output equal to 3. And that is the advantage to be noted. Suppose we don't want to create.
this variable as global, and we don't want it to be visible to other functions within this file.
Then declaring it as a local to this function, makes it visible within this function only and
the other functions within this file, would not be able to see this variable. And that is the advantage you are
getting from this static int count. Even though it is declared as a local variable to this function
still I would be able to retain its value. Because this variable is static in nature. And it wont change.
When I call this function once again, then this variable doesn't get destroyed. And that is the biggest
advantage of using this variable with static key word. Now, there is one more point
that I would like to mention. Suppose I initialized it to a constant value,
like 3. I save this file and I debug the code. Then the value we got is equal to 6,
which is acceptable. Now suppose, I declare another variable integer var equal to 3.
And what I am going to do is I am going to assign this variable to this count variable.
Then what is going to be the output in this case? Here you can see, you got an error.
"Initializer element is not constant". Here, you initialize it to some variable right?
This variable count is initialized with a variable. Now this is one thing that we need to note.
Always, a static integer variable is assigned with a constant value and not a variable
or any function. It must always be a constant value. Now, here are the takeaways for this lesson.
Static variable remains in memory even if it is declared within a block on the other hand,
automatic variable is destroyed after the completion of function in which it was declared.
Static variable if declared outside the scope of any function will act as global variable
but only within the file in which it is declared. You can only assign a constant
literal (or value) to a static variable. And you will not be able to assign
a variable to a static variable. or a function return value to a static variable.
OK friends, This is it for now. See you in the next lecture.
Bye.
Automatic variables are local to a function, reinitialized each time it runs, and destroyed when the function exits. Global variables exist for the program's lifetime and are accessible from any file, retaining their values across function calls. Static variables can be either global or local but have restricted scope: static global variables are limited to the declaring file, and static local variables retain their value between function calls while being accessible only within their function.
Declaring a global variable as static limits its visibility to the file it is defined in, preventing other files from accessing or modifying it. This reduces the risk of unintended side-effects or bugs caused by external manipulation while maintaining the variable’s state throughout the program’s execution.
Local automatic variables are reinitialized each time the function is called and destroyed when it exits, so they don’t preserve values between calls. Using the static keyword on a local variable makes it retain its value across multiple calls, as it is initialized only once and exists for the program's lifetime, while still restricting its scope to the function.
No, static variables must be initialized with constant literals at the point of declaration. They cannot be initialized using variables, function return values, or expressions that are evaluated at runtime. This ensures their initial value is determined at compile-time and remains consistent throughout execution.
Declare the count variable as a static local variable inside the increment function, like static int count = 0;. This way, count retains its value between function calls but remains inaccessible from other functions or files, providing controlled state retention while encapsulating the variable scope.
Global variables without the static modifier are accessible and modifiable across all source files, increasing the chance of unintentional changes leading to bugs or unpredictable behaviour. This unrestricted access makes code harder to debug and maintain, especially as projects grow in size.
Use static local variables when you need to preserve state within a single function without exposing the variable externally, promoting encapsulation and reducing namespace pollution. Static global variables are more suitable when a variable needs to maintain state across multiple functions within the same file but should remain hidden from other files.
Heads up!
This summary and transcript were automatically generated using AI with the Free YouTube Transcript Summary Tool by LunaNotes.
Generate a summary for freeRelated Summaries
Understanding Static Variables and Memory Segments in C Programming
This detailed explanation explores the behavior of static variables in C, focusing on how their initialization affects storage in different memory segments like BSS and data segments. It also covers hexadecimal notation, format specifiers, and the memory layout of C programs, with practical examples and compilation insights for better comprehension.
Understanding Variables in C Programming: Declaration, Initialization, and Usage
This lesson introduces the concept of variables in C programming, explaining their declaration, definition, initialization, and how to use them effectively. Learn how variables act as memory storage with simple examples and best practices to manage variable values within your programs.
Understanding Variable Scope: Local vs Global Variables in Programming
Explore the concept of variable scope in programming, focusing on the differences between local and global variables. Learn how variable lifetime and visibility affect program behaviour with clear examples and key principles.
Mastering Constants in C: Defining and Using Macros Effectively
Explore how constants are defined and utilized in C programming using #define and const keywords. Learn best practices, common pitfalls, macro functions, multi-line macros, and predefined macros for date and time to write clean, maintainable code.
Essential C Programming Variable Naming Rules and Best Practices
This summary highlights the crucial rules and conventions for naming variables in C programming, emphasizing why proper naming is vital for effective coding. It covers valid characters, case sensitivity, forbidden keywords, and practical tips to avoid common mistakes and improve code readability.
Most Viewed Summaries
Kolonyalismo at Imperyalismo: Ang Kasaysayan ng Pagsakop sa Pilipinas
Tuklasin ang kasaysayan ng kolonyalismo at imperyalismo sa Pilipinas sa pamamagitan ni Ferdinand Magellan.
A Comprehensive Guide to Using Stable Diffusion Forge UI
Explore the Stable Diffusion Forge UI, customizable settings, models, and more to enhance your image generation experience.
Pamamaraan at Patakarang Kolonyal ng mga Espanyol sa Pilipinas
Tuklasin ang mga pamamaraan at patakaran ng mga Espanyol sa Pilipinas, at ang epekto nito sa mga Pilipino.
Mastering Inpainting with Stable Diffusion: Fix Mistakes and Enhance Your Images
Learn to fix mistakes and enhance images with Stable Diffusion's inpainting features effectively.
Pamaraan at Patakarang Kolonyal ng mga Espanyol sa Pilipinas
Tuklasin ang mga pamamaraan at patakarang kolonyal ng mga Espanyol sa Pilipinas at ang mga epekto nito sa mga Pilipino.

