Static Variables In C And C++ – Function Level

We’ve looked at file level static variables, so now let’s see what happens when you put them in a function.

If you declare a static variable at function level (i.e. inside an normal function, not a class method), then you are creating a variable that will:

a) be instantiated the first time the function is actually called, and
b) retain its value after the function exits.

The variable is only accessible inside the function it is declared in.

Read moreStatic Variables In C And C++ – Function Level

Static Variables in C and C++ – File Level

When is a global not a global? When it’s a static variable.

This post, and the next three, will talk about static variables. Let’s start with static variables declared in a file.

Static variables in a file

If you declare a static variable at file level (i.e. not inside any other code), then you are creating a so-called “global” variable that will:

  1. be available for the entire duration of your program, and
  2. be accessible only from that translation (compilation) unit (i.e. the file itself and any file that includes it).

Number two is the important one here. It means that if you include (say) a header that contains a static variable in two different source files, you will end up with two “global” variables with the same name.

Read moreStatic Variables in C and C++ – File Level

Friend Functions And Classes In C++

The friend keyword in C++ is one of those concepts that is formally taught, but then seems to disappear off the scene once you get into the real world. Maybe friends are less common in embedded programming (ha ha), but I’ve seen very few of them over the years.

The thing is, they just don’t seem to be at the forefront of people’s minds when writing code. When would you ever actually use one of these things?

Aren’t they just a way to avoid writing getters and setters??

I think when you are learning a language, understanding concrete examples of why a concept is there is absolutely necessary if that concept is to stick and be used well.

So let’s have a look at friend functions and classes and see what on earth we could do with them.

Read moreFriend Functions And Classes In C++

Inclusion Guards

Just to clear up what we’re talking about, an inclusion guard looks like this:

#ifndef HEADER_FILE_H
#define HEADER_FILE_H

...//your header

#endif //HEADER_FILE_H

It consists of three preprocessor directives around the code of your header file.

Most IDEs add these for you automatically when you create a header, but it’s well worth having an appreciation of why they are there.

Read moreInclusion Guards