Synfire's Guide to C++

3. Variable Basics

Variables are memory locations that have been given a name that stores certain information, depending on what type was specified. Make sure that you define a variable and give it a type. The different types contain a lot of technical information that later on you should remember, but for now I think I can slide by in giving a brief definition of the different types:

holds a small numerical value (2 bytes)
holds a numerical value, on some computers it is larger than a short, but not always, I suggest for any small number just use an int don't worry about short. (2 or 4 bytes)
holds a slightly larger numeric value but depending on the endianness of the computer could be the same as int. (4 bytes)
holds numerical values with decimal points such as 3.14
holds large numerical values with decimal points such as 3.141592653
holds a single character value (1 byte)
holds either a true value or a false value.

Now this should suffice but there is one thing, on all these types except for char, the numerical ones in other words, you can further specify your needs through the 'signed' and 'unsigned' prefixes. Signed types only allow the variable to hold negative data, while unsigned types can only hold positive. Unsigned is used a lot for Ages, because you can't be -13 years old!

So you may be asking yourself how do I create a variable?

Well first thing you must define the variable, then you can assign a value to it and use it any way you want. Unfortunately there are a few rules to naming variables, first you can't have spaces in your variable name (use an '_' character if you wanna space), second you can't use any special characters like !@#$%^&*()?, and last but not least you MUST start your variable with a letter, You can use numbers, but the first character must be a letter. I suggest using the camels back technique that I use in this tutorial. Now that I have explained the rules, lets play ball...

#include <iostream.h>

int VarInt;
// This has created an int variable called VarInt

unsigned int PosVar;
// This created a variable int that can only hold
// positive numbers

signed int NegVar;
// This created a variable int that can only hold
// negative numbers

double Pi = 3.14;
// This has created a double and assigned the value 3.14 to it

int main()
    cout << "Enter a positive number: ";
    cin >> PosVar;
    cout << "Enter a negative number: ";
    cin >> NegVar;
    cout << "Enter a number negative or positve: ";
    cin >> VarInt;
    cout << "PosVar: " << PosVar << endl;
    cout << "NegVar: " << NegVar << endl;
    cout << "VarInt: " << VarInt << endl;
    cout << "Pi: " << Pi << endl;
    return 0;
This should be a good example of how to use variables. Basically, define a variable, these are called global (any part of the program can use them) variables. You could also use local (only the function that the variable is in can use them) variables by moving the 'int VarInt;' or whatever into the function that you need them in. This will be discussed in chapter 6 Functions.

Now that we have gone over normal variables, it is time to go into constants. Constants are variables that the value defined is never changed. You should use constants anywhere that a variable has a defined value that should not be changed. An example of this is a program that finds the area of a circle.

#include <iostream.h>

const double PI = 3.14;
// this makes a double named PI with the value of 3.14
// that cannot be changed.

const int TWO = 2;
// this makes an int named TWO with the value of 2
// that cannot be changed.

long Radius;
// this makes a long named Radius that it's value
// CAN be changed.

float Area;
// this makes a float named Area that it's value
// CAN be changed.

int main()
    cout << "Enter the Radius: ";
    cin >> Radius;
    // this next part may look a little Greek for now
    // but this is just to demonstrate that the PI and
    // TWO are not changed.
    Area = (Radius * TWO)* PI;
    cout << "The area is: " << Area;
    return 0;

Okay that should be all for the constants that you need. Lets move on to something that makes programming a pain in the ass. This is straight up memory allocation and management. What am I talking about? Well a thing we call pointers. Pointers are variables that hold a specific memory address. When called they will return what ever is in that memory address. Time for and example:

#include <iostream.h>

int main()
    int * p = 0; // The pointer is initiated to hold
             // data the size of an int. Then the
             // pointer is assigned to 0. Don't ask
             // Why just always do it that way.

    int a;
    cout << "a: ";
    cin >> a;
    p = &a // The & operator is also known as the 'address'
        // operator. If it is put in front of a variable
        // then the variable returns it's address instead
        // of the data held in that address. Here we see 
        // the address of a is being assigned to p;

    cout <<  "*p: " << *p; // The * before a pointer makes the pointer
               // return the value stored in the address
               // that the pointer is holding.

    cout  << "p: " << p; // Without the * the pointer just returns
             // the address that it is holding.

    cout << "*p: ";
    cin >> *p; // Note the * in front of the pointer, this tells you that
           // you are assigning the input to the address, and not the
           // pointer.

    cout << "a: " << a;     // If this was compiled and ran this would
                // return the value you just assigned to the
                // *p.

    return 0;
Okay now is where you ask me, "WTF? Why would I want to create just another name for my variable??" and my response would be, "You wouldn't :)" then you would give me a weird look and think I and stroustrup were both insane. Well, even though you got half of that right, this demonstration is only good for what I just did, a demonstration. BUT this does let you get acquainted with the syntax, so now we can actually put pointers to some use...

Why would you use pointers?

  1. Managing data on the free store.
  2. Accessing class member data and functions.
  3. Passing variables by reference to functions.

Allocating, using, and deleting pointers.

#include <iostream.h>

int main()
    int Var = 3;
    int * Pointer2Var = &Var;
    int * Pointer2FS = new int;
    if(Pointer2FS == NULL)
     cout << "ERROR: Not Enough Memory!" << endl;
     return 0;
    *Pointer2FS = 5;
    cout << "Var: " << Var << endl;
    cout << "Pointer2FS: " << *Pointer2FS << endl;
    cout << "Pointer2Var: " << *Pointer2Var << endl;
    delete Pointer2FS;
    Pointer2FS = new int;
    if(Pointer2FS == NULL)
     cout << "ERROR: Not Enough Memory!" << endl;
     return 0;
    *Pointer2FS = 9;
    cout << "Pointer2FS: " << *Pointer2FS << endl;
    delete Pointer2FS;
    return 0;

Okay, I know there are no comments but that is because I plan to explain this slowly and not on the fly. The downfall of local variables is that when you return from a function all local variables are thrown away. Putting data on the free store using pointers solves this problem, the reason behind this is that data on the free store cannot be thrown away it must be deleted by the programmer.

CAUTION: Be very careful when working with pointers to the free store, a rule of thumb is before you reassign a pointer make sure you delete it. Failure to do so is what calls memory leaks.

Now that I have given you the warnings let me explain what is going on here.

First, on line 6, we create a pointer with the memory address of Var, as I stated before this is mostly useless except for examples...
Then, on line 7, we create a pointer to the free store the size of an int. This is done using the 'new' keyword, 'new' allocates a place in memory the size of the argument passed, in this case 'int'.
Next, on lines 8 - 12, a test is preformed to see if you have enough memory left to create the pointer. This is important to do, every time you create a pointer to the free store you should test it to make sure that you will be able to place the data there, if not then the program should print an error message and exit the program (This is why it is considered good practice to use 'int main()' so that you can 'return 0;' when an error occurs to stop the program on the spot.
Now, on line 13, we place the value 5 on the free store.
The next few lines show that you can use the pointer to the free store just like a variable.
Then, on line 17, we decide that we want to give the pointer a new value, so we first use the 'delete' command to clear up the address, then, on line 18, we use new to initialize the space for the free store once again.
The test is ran again on lines 19 - 23.
And, on line 24, we reassign a value to the pointer.
Before the program ends we use the delete command again to make sure we don't end up with a memory leak, and we exit the program. Now that wasn't so hard now was it. ;) Study it a few more times and continue on.

For now I want you to just get familiar with the above syntax. DO NOT CONTINUE WITHOUT LEARNING THIS! Later on we will get into actually doing some of these three and if you don't know pointers you will be lost beyond belief! Just take a few hours and REALLY study this section then move on.

In this section you learned how to define and use variables, constants, and pointers. You also learned how to allocate memory on the free store.

< < < Lesson 2: cout and cin | Lesson 4: Conditional Statements > > >

Want some naughty smileys for your Yahoo messenger? Then look HERE.