Static Variables In C++ Classes

It turns out that static variables in C++ classes are actually pretty cool.

If you declare a static variable at class level (i.e. inside the class declaration), then you are creating a variable that will

a) be accessible to all objects created from that class, and
b) be available even before you have created a single instance of that class.

Essentially, every object you create sees the same static variable, so anything that one object does to that variable (such as increment the value), all the other objects can also see.

Super useful, eh?

Read More »



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 More »



Getting Started With C Programming – Hello World Tutorial

If you’ve always wanted to dabble in C, but never quite gotten around to it, have a read through this and give it a go.

It is much easier than you might think (easier now, in fact, than it ever has been), to write your first C program, and there is something so deliciously inviting about the language that once you get started you’ll soon be solving world issues with your code.

To follow along with me:

You will need

  1. A computer running a Linux variant (I use Fedora)
  2. A compiler
  3. This walkthrough

Read More »



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 More »