Lesson 4: Variables

If you’re exceptionally clever, you’ve probably come up with some questions by now.

Something like: “Do we have to explicitly write out what we want to print like in the hello world lesson?” or “iostream means input/output stream, does that mean we can get input from the user and store that information somehow?”

Wait… you weren’t thinking those questions?  Oh well, I’m going to discuss them in this lesson regardless!

TL;DR – variables are place holders that store stuff.

Now to get into the nitty-gritty. I’m going to cover the following:

  1. A little background on why we use variables.
  2. How to declare a variable.
  3. Variable name format.
  4. Overview of variable types.
  5. Local and global variables.
  6. Examples (throughout post).

A little background:

Computers use a CPU and RAM (random access memory) to run your program.  The CPU executes your program and works with RAM to obtain information that needs to be executed. Binary code and the data associated with it.

RAM can be visualized like a neighborhood street with houses running down either side.  The houses are locations in memory.  These houses store things and each has an address.  To access a specific location, to get something stored there, the CPU needs to be give the address and asked to fetch data.  Or vice-versa, write data to that address.

You will be storing information in variables and that information will be assigned a memory address.  The variable name is a friendly name that allows the computer to know where that information is being stored.

Declaring a variable

When declaring a variable in a language like C++, you don’t actually have to give the explicit address of where you want that information stored in memory.  If you actually had to provide an address for each variable, there would be the problem of it being very time consuming.  Also, if you picked a random memory address you’d run the possibility of overwriting information already at that location!

We do not want to say: “Hey computer, store the number 50 at ‘1313 Hanover Street'”

  • This is too explicit.  The computer will go to that address, kick out its occupants, and store 50 there.  This could break other things that relied on the information stored at 1313 Hanover.  It would also require you pulling up a map and figuring out an address on that street.

We want to say: “Hey computer, store the integer 50 at ‘myVariable'”

  • The computer will say “OK, I have an integer type, and I need to store it in open memory.  1313 Hanover is occupied, so I’ll stick this integer at 3541 Buffalo Street, which is currently not occupied.”  This is more flexible, safer, and quicker (you can make up your own variable names, so no need to look up a map to find viable addresses).

You declare variables in the following pattern.  Initializing the variable (providing InitialValue) is good programming practice, even if the initial value is zero.

[VariableType] [VariableName] = [InitialValue];
or
[VariableType] [VariableName];

int myTestVariable = 4;        //camelCase variable initialized to 4;
int my_second_variable = 30;   //underscore_notation variable initialized to 30;
int mySum = myTestVariable + my_second_variable;  //mySum variable initialized to the sum of our other two variables

 

VariableName and Format

This is a friendly name, 100% made up by YOU, to represent the variable.  We will use the VariableName later in our program to access the specific “house” or memory location to gather our desired information.

You should pick one of these two styles when creating VariableNames for your program.  This just helps with fluidity of the program, it does not affect functionality.

  1. Camel case: thisIsAnExampleOfCamelCase
    1. Basically start the variable with lower case and every subsequent word has its first letter uppercase.  No spaces between words.
  2. Underscore notation: this_is_an_example_of_underscore_notation
    1. All lowercase with underscore separating words.

NOTE:

  1. Do not mix camel case and underscore notation in the same program.  It makes following the code more difficult if someone needs to go through it in the future.
  2. In C++, variable names can be alphanumeric, but cannot start with a number.
  3. They cannot contain spaces.
  4. They cannot contain arithmetic operators such as +, -, /
  5. They cannot be reserved keywords. Like “return” or “cout”

Overview of Variable Types

The VariableType lets the compiler know the data type of the variable (pretty strait forward).  With this knowledge, the compiler reserves the necessary space for that variable on the fly.  Here is a list of variable types and some basic info on them.

  1. int – standard integer: 1, 5, 100, 457, etc… No decimals.
  2. float – single-precision floating point value: 1.1, 5.3, 654.1, 9.7563
  3. double – double-precision floating point value:  best to be used when you have extremely large floating point values.
  4. void – represents the absence of type.
  5. bool – stores value of true or false.
  6. char – typically a single octet (one byte).  int type.
  7. wchar_t – wide character type.

 

Scope of Variables – Local and Global

Variables do have a defined scope.  This means that if the variable is used outsdie of its scope, the compiler doesn’t know what the variable is and fails to build.

Below, I will show you some example code setting local and global variables.

Local Variables

This means that they are declared within a function.

These variables can only be used within whatever function they are defined in. In this example, they are declared within the main() function.

int main()
{
    int a = 96;        //local variable
    int b = 38;        //local variable
    int sum = a + b;   //local variable
    std::cout << sum << std::endl;
    return 0;
}

 

Global

As you can see, a and b are defined outside of a function in this example, which makes them global.

This means that they can be used in different functions that you create.

I created a test() function below and used the same variables that were used in the main() function.

int a = 96;  //global variable
int b = 38;  //global variable

int main()
{
    int sum = a + b;  //local variable
    std::cout << sum << std::endl;
    test();
    return 0;
}

int test()
{
    int sum2 = a * b;
    std::cout << sum2 << std::endl;
    return 0;
}

 

If you have any questions or concerns, please let me know below in the comments section.

 

Until we meet again fellow knowledge seekers!

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s