How to Understand Static Variables/Function in C

Static Storage: static, the same with global variables.

They will be Initialized to 0 because they are in static area.

There are three kinds of staitc variable/function:static local variable, static global variable, static function. I will introduce the life cycle, scope, usage.

Static Local Variable

What is a static local variable? Please refer to the following code.

#include <stdio.h>

int getNumber()
{
	static int number = 0;
	number++;
	return number;
}
int main()
{
	for (int i = 0; i < 10; i++) {
		printf("Number is %d\n", getNumber());
	}
	return 0;
}

Output:

Number is 1
Number is 2
Number is 3
Number is 4
Number is 5
Number is 6
Number is 7
Number is 8
Number is 9
Number is 10

Refer to “Static int number = 0;”, we can know number is a static local variable.

Usage: I assume that you have already noticed the value of number is incremental instead of fixed 1 because the value is storaged in static instead of stack and that is initialized only once.

Scope: They are visible only within the block or function like local variables.

Life Cycle: They are destroyed only When the whole program is over, which is defferent with auto variables.

Static Global Variable

Prototype:

#include <stdio.h>
static int number = 3;

int main()
{
        printf("static number = %d\n", number);
	return 0;
}

Usage: Static global variable can be used as a global variable in current file. Any functions in this file can use this variable. But functions in the other files can’t invoke this static global variable, which is the most difference between global variables and static global variables.

Scope: They are visiable only within the current file.

Life Cycle: They are destroyed only When the whole program is over, which is defferent with auto variables.

Static Function

Prototype:

#include <stdio.h>

static int getNumber(int i)
{
	return i + 1;
}
int main()
{
	for (int i = 0; i < 10; i++) {
		printf("Number is %d\n", getNumber(i));
	}
	return 0;
}

Usage: Static functions can be invoked only by functions in current file.

Scope: They are visiable only within the current file.

Life Cycle: They are destroyed only When the whole program is over, which is defferent with auto variables.

Note: The non-static functions or global variables can be invoked by functions in other files. In additional to expose the interface in related xxx.h files, we also can use “extern” words. If you’d like to know about “extern” word, you can refer to the following post.

How to Understand “extern” Keyword in C (example)

Reference:

https://www.careerride.com/C-static-variables-scope.aspx

Have a good day!

If you have any question, please feel free to let me know. I will appreciate it if you give me some feedback!

Share this article to your social media
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments