3 minute briefing on variables

Next Tuesday we are going to code a little more, and I wanted to give you a simple intro into C++.  However, C++ requires more than a simple intro, but just so that you can tag along with what is going on I am going to give a set of these briefings. This one is about variables.

Variables are used to store data in them … nothing more nothing less. But C++ is very narrow minded about what type of data each variable can store, you can not simply write everything into any variable – everything has to go where it belongs. That is why variables have types. The second thing C++ insists on is knowing beforehand that you want to use a particular variable, you can not simply say “store this value here!”, the “here” has to be defined well beforehand. That is why somewhere close to the top of your program you see things like this:

int i;
float f;
double d;
char c;

The above piece of code does nothing else than telling the compiler it would like to use a couple of variables called i,f,d, and c. It also makes sure that these four variables have four different types int (for integers that are whole numbers -2, 0, 12231, …), float and double (which are floating point numbers like 0.00121, 123.2, …) where the only difference is the precision because doubles are “twice” as accurate than floats, and lastly a char (which is a character that stores letters like ‘a’,’t’, or the character ‘0’).

Whenever you want to assign a value to a variable you need the = sign. It will take whatever is to the right of it, evaluate it, and dump it in whatever is on the left side of the equal sign. But what does “evaluate” mean in this context? Simply put, it performs the math that you might potentially want to do. Check out the following piece of code which makes it more obvious I hope:

i=5;
// now i has the value 5 stored in it
i=(5+5)*(7-1);
// now i has the value 60 stored in it, the 5 that it held before is gone
i=i-30;
// i is now 30, because the right hand side was evaluated first, and at that moment i was still 60

So far so good, now to somewhat more complex variables, namely arrays. Arrays or vectors were invented to allow variables to have an index and to make lists. Check out this piece of code:

int a[10];
a[1]=656;
a[3]=0;

Instead of making a single variable a, which is supposed to be an int, the [] blocky brackets create as many of these a’s as stated within the brackets. In this case you get ten variables a, and in order to differentiate between them, you can use the [] again to tell them apart. a[0] is the first one, followed by a[1], and the last in the bunch is a[9] – and yes C++ starts counting at 0.

Last one: Instead of specifying elements in an array with a constant value like a[0] you can replace the 0 with another variable:

int a[10];
int i;
i=9;
a[i]=i;

This will set the value of a[9] to 9. I let this sink in for a moment. Next time I talk about fancier ways of making arrays.
Cheers Arend

Leave a Reply