Static Variables in C

Last Updated Nov 1, 2015, 07:00:14 PM





A static variable is a variable whose memory is allocated at compile time. The keyword static is used to declare a static variable in C

Static variables are not the default class of global variables, and the variable allocation takes place first at the time of program execution. A static variable is access quantifier that can limit the scope however it also cause the variable to exist for the lifetime of the program. Meaning, the static variable can not be seen outside the function.

The static variable value is persisted between all the success calls made to the function.

The address of the static variables can be passed to other modules and function in other C programs or files.

Static variable can be delcared many times but it can be initialized only once.

Static Variable Example in C

Try It Now

In the above program, we've declared the same static variable multiple times but we initialized the variable only one time. That is an important thing to remember

The value of an integer type static variable is zero or null. See the below example

Try It Now

Few Important Points About Static Variables
  • Static variables can be declared as many times but it can be initialized only once
  • The default value of integer type variable is zero otherwise null
  • The visiblity of a static variable declared locally is within the block where it was declared
  • If a static variable declared gloablly then its visibility is only within the file it was declared.
ProTip!

Static is also used to define class attributes which can be shared between all objects of the same class



Other Variable Topics you might want to learn

Global Variables in C

Static Variabls in C

Difference between Static and Global Variables- StackOverFlow