Static Variables In C Language

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

In C, the static keyword can be used to create a static variable, which is a variable that retains its value between function calls. A static variable is initialized only once, when the program starts, and its value is preserved until the end of the program.

A static variable is defined by using the static keyword before the variable's data type. Here is an example of how to declare a static variable:

Copy code

static int counter = 0;

A static variable can be defined in the global scope or inside a function. When a static variable is defined inside a function, it is only accessible within that function and its value is retained between function calls.

Copy code

void func() {    static int num = 0;    num++;    printf("%d", num); }

When the function is called multiple times, the value of the variable "num" will be retained, it will not be reset to 0 as a local variable would.

It's important to note that static variables are only initialized once, when the program starts, and their values are not affected by function calls. This makes them useful for maintaining state information, for example, counting the number of times a function is called or maintaining a running total.

Additionally, when a static variable is defined in the global scope, it's only accessible within the source file in which it's defined and it's not visible to other source files. This makes it useful for creating hidden variables that are only accessible within a specific source file, which can help to encapsulate the implementation details of a program.

2. Variable and Data Types

Comments: 0

Frequently Asked Questions (FAQs)

How do I register on Sciaku.com?
How can I enroll in a course on Sciaku.com?
Are there free courses available on Sciaku.com?
How do I purchase a paid course on Sciaku.com?
What payment methods are accepted on Sciaku.com?
How will I access the course content after purchasing a course?
How long do I have access to a purchased course on Sciaku.com?
How do I contact the admin for assistance or support?
Can I get a refund for a course I've purchased?
How does the admin grant access to a course after payment?