Learn C Language – Part 7: Static Variables

Static variables in C.

Sooooooo, this is the very last section of Learn C Language series. It has been a long ride, but it was a rewarding journey, wasn’t it? In the last section, we’ll take a look at how static variables are used in C, and take an even loser look at how we should handle it.

Here, this is the very end of Learn C Language series. I think I’ve been through most of the core concepts of the language via this series. And the rest is all up to your dedication to improving your skills. And also, along with this series, I’ve been posting another series coding in C, including Linux Programming and Arduino, so if you’re interested, you can also have a look at the,m as well.

Anyways, let’s dive into the very last section of Learn C Language!

Static variable

image 01

in image 01, static int num = 0; is declared in foo().

Even though the static variable is declared within foo(), it can act as if it were a global variable.

static int num = 0; in line 14 is only executed for the first time and won’t be executed for the rest of the executing process.

The result

image 02

And this is the executed result.

Static variable’s characteristic

image 03

Since static variables are hidden from other parts of the source code, the num in line 15 is a global variable that can be used only within foo() method, so to speak.

So, just like the simple in image 03, it fails to access the num variable from main().

Leave a Reply