C++ Tutorial for noobs - Part 4: Variables

...Back to Part 3: Data-Types


Okay, let's just jump into the cold water and get to the point. A variable is pretty much the same as a bottle:

So if our bottle is a water bottle, then we can put all kinds of water into it. If our variable is a int variable, then we can put all kinds of numbers into it.

Since we can have more than one Variable, we will give each one a name like 'someVariable' or maybe even something short like 'n' or 'm':

C++ variables always have a Data-Type like:

int n;

Note: in C++ there has to be a semicolon after each instruction.

Basic Structure

Now if we do something like:

int n = 42;

This means that n now contains the number 42. Or we put 42 into n, or n becomes 42, or however we want to call it.

We might as well use a number:

int n = 42;

Our variable n now contains the number 42.

It's pretty much the same pattern all the time:


Using multiple Variables

We can do some really cool things like this:

int n = 42;
int m = n + 1;

So what happens is this:

Which means that in the end, n is 42 and m is 43.

Note: C++ code is processed from the top to the bottom, one line after another.

Re-using a Variable

To make our lives easier, C++ allows us to use the same variable multiple times:

int n = 42;
n = n + 1;

If we look carefully, we can see that:

Note: when using a variable for the second time, we don't have to specify its type again (as seen in the above example).

And that is all there is to know about variables. Whatever is one the left side of the = sign becomes whatever is on the right side of the = sign. It's really that easy!

Continue to Part 5: Functions...