What is static variables in C?

Static variables have a property of preserving their value even after they are out of their scope! Hence, static variables preserve their previous value in their previous scope and are not initialized again in the new scope. 

Syntax:

In C programming language, a static variable is a variable that retains its value even after the function or block where it was declared has completed its execution. In other words, static variables have a lifetime that spans across the entire program's execution, as opposed to automatic variables, which are destroyed as soon as their enclosing function or block terminates.

To declare a static variable in C, the keyword "static" must be added before the variable's type in the declaration. For example, to declare a static integer variable called "count" with an initial value of zero, we can use the following code:

 

static int count = 0;

Static variables are commonly used to implement counters or accumulators, as well as to maintain state information across function calls. They can also be used to share data between different functions within the same file, without making the variable global and exposing it to other files.

It is important to note that static variables have a default initial value of zero if they are not explicitly initialized. Also, their scope is limited to the block or function where they are defined, and they cannot be accessed from other files unless they are declared as external variables using the "extern" keyword.

Submit Your Programming Assignment Details