# Chapter 6 – Variables

## 6.1  Variables Defined

Variables are used by programs to store data.  Their values can be set, and changed as often as needed.  Before you can use a variable, it must be declared.  When you declare a variable, you reserve a memory location on the computer and assign a name to it.  This memory location holds the variable's value.  The following line declares an integer variable named Age.

int Age;

Declaring an integer variable such as this reserves four bytes of memory for storing its value.  An integer is a number without a decimal point – e.g. 3, 1492, -200, 0, or -1.  Once the variable is declared, you may assign it a value.  The following line is an example assignment statement.

Age = 25;

The previous line assigns the value of 25 to the variable Age.  The next assignment statement adds 5 to the existing value of Age, thus making it equal to 30.

Age = Age + 5;

Below is a completed program using the integer variable Age.

 Program 6.1 – Using Variables #include using namespace std; main() {   int Age;   Age = 25;   Age = Age + 5;   cout << Age << endl; } Output 30

Summary

• Variables are used to store data used in a program.

• Before a variable can be used, it must be declared – you put the variable type followed by the variable name.  The following example declares an integer variable named Age:

int Age;

• An assignment statement is used to assign a value to a variable.  An assignment statement consists of the variable name, an equal sign, and then the new value.

Age = 25;

• Assignment statements can contain mathematical expressions.  They may also use the same variable in the expression.  The assignment statement below assigns the value of 10 to Age (assuming Age was previously equal to 25).

Age = Age / 5 + 5;

## 6.2  Variable Names

When declaring a variable, you assign it a name (e.g. Age).  Legal variable names must begin with a letter or an underscore, and can contain any combination of letters, numbers, and underscores.  Variable names cannot contain spaces or symbols.  Variables cannot be named after C++ keywords – e.g. cout, cin, if, else, for, while, int, float.

 Legal Variable Name Illegal Variable Name X cout Car1 1Car My_Age My Age HelloWorld HelloWorld!

When choosing a variable name, be descriptive.  For example, if you are writing an accounting program, use variable names like Assets and Liability instead of A and L.  A good naming convention is to capitalize each word in your variable names.  For example: Height_Pyramid, Width_Pyramid, Length_Pyramid.  Remember, variable names are case sensitive – Age is a different variable than age.

## 6.3  Variable Types

In the first program, we used the int variable type.  An integer is positive or negative whole number (does not contain a decimal point).  The following table lists the different C++ variable types.

 C++ Variable Types Variable Type Size Legal Values Comments int 4 bytes -2,147,483,648 to 2,147,483,647 For most compilers, int is the same as long int – a four byte integer. short int 2 bytes -32,768 to 32,767 This is useful for smaller numbers and uses half as much memory as a regular integer. unsigned int 4 bytes 0 to 4,294,967,295 This is useful for larger numbers that are not negative. unsigned short int 2 bytes 0 to 65,535 This is useful for smaller numbers that are not negative. float 4 bytes -1.2e -38 to 3.4e38 A float variable has a floating point, meaning there is a decimal point with a variable number of digits past it – e.g. 3.34, -123.456, 2.0. double 8 bytes -2.2e-308 to 1.8e308 Double precision variables are for very large numbers, and usually written in scientific notation. bool 1 byte true or false Boolean variables are used for things that are either true or false, such as whether or not someone is a citizen. char 1 byte one alphanumeric digit A char is one alphanumeric digit, as shown in the ASCII chart.

How do you choose the right variable type?  As a general rule, integers are used for numbers without a decimal point.  Floating points are used for numbers that have digits past the decimal point.  Double precision variables are for very large and small numbers.  Character variables are used for storing a single alpha-numeric character.  This includes letters of the alphabet, numbers, symbols, etc.  Boolean variables are used for storing information that is either true or false, such as whether or not you have traveled abroad.

In choosing a variable type, you should use the type which requires the least amount of memory.  As can be seen in the previous table, an int variable requires twice as much memory as a short int.  Should you be concerned about saving two bytes of memory?  For the programs in this book which only declare a few variables at most, saving memory is not a concern.  More advanced programs may declare hundreds, thousands, or millions of variables – conserving memory is a concern.  If there is any chance that the value you assign to the variable will be larger than its type, use the larger variable type (e.g. use int instead of short int).

## 6.4  Using Integer Variables

The next program demonstrates using the int variable.

 Program 6.4a – Integer Variable #include using namespace std; main() {   short int Apple;   short int Pear;   Apple = 5;   Pear = 6;   cout << Apple * Pear << endl; } Output 30

The next program is similar to the previous.  Both variables (Apple and Pear) are declared in one line by separating the variable names with commas.  Also, values may be assigned to the variables in the declaration line.

 Program 6.4b – Declaring Multiple Variables and Assigning Values #include using namespace std; main() {   short int Apple = 5, Pear = 6;   cout << Apple * Pear << endl; } Output 30

Be careful when using integers that you do not assign a value above the largest legal value or below the smallest legal value.  If you do, the value will "wrap around".  In the next program, we declare a short int and make it equal to its maximum legal value.  Incrementing (adding 1) the variable causes the value to wrap around and become its smallest legal value.

 Program 6.4c – Wrapping Around an Integer // A short int variable has a range of -32,768 to 32,767. // This program declares a short int variable and makes it // equal to the largest value it can be.  The program then // adds one to the variable to demonstrate what happens // when it goes past the upper limit.   #include using namespace std;   main() {   short int Test = 32767;   Test = Test + 1;   cout << Test << endl; } Output -32768

When you add 1 to the value of a variable, it is called incrementing the variable.  When you subtract 1 from the value, it is called decrementing the variable.  In the previous program, we increment the variable Test:

Test = Test + 1;

An easier way to increment Test is to do the following:

Test++;

You can also decrement (subtract 1) a variable by following its name with two minus sings:

Test--;

This is where the C++ programming language gets its name.  The C programming language was the predecessor to C++.  Therefore, the next version of C is C + 1, or C++.  The title of this book, C++ for Geniuses-- uses a decrement (minus-minus) on the word "Geniuses", meaning for the not-so-genius.  If you are in fact a genius, then you might want to return the book.  If you were a genius, however, then you would have known this and not purchased the book in the first place.  Therefore...

## 6.5  Using Float Variables

For numbers that have a decimal point, the float variable type is used, as shown in the next program.

 Program 6.5a – Float Variable #include using namespace std; main() {   float A = 1.5, B = 2.44, C;   C = A + B;   cout << C << endl; } Output 3.94

It is good practice to always type the decimal point when using float variables.  The next program demonstrates how failing to type the decimal point may give you unexpected results.  When the compiler divides 1 / 4, it assumes the result is an integer since both variables are integers.  To correct the program, change the assignment statement to: A = 1.0 / 4.0;

 Program 6.5b – Remember to Type Decimal Point #include using namespace std; main() {   float A;   A = 1 / 4;   cout << A << endl; } Output 0

## 6.6  Using Char Variables

A char variable stores a single alphanumeric character.  You must use single quotes when assigning a char variable a value.  The following program demonstrates this variable.

 Program 6.6 – Char Variables #include using namespace std; main() {   char MyGrade = 'A';   cout << "My Grade is an " << MyGrade << endl; } Output My Grade is an A

## Exercises – Chapter 6

 What type of variable would be most appropriate for storing each of the following, keeping in mind to conserve memory whenever possible? 1. Someone's age 2. The balance of your bank account 3. The yearly budget for the U.S. 4. A person's gender 5. A car's odometer reading 6. Whether or not someone has a driver's license 7. The distance in miles to other stars in the galaxy 8. The outdoor temperature

What will each of the following output?

 9.   cout << 1 / 4; 12.  int Cow = 4, Chicken = 6;      Cow = (Cow * 4) % 2;      cout << Chicken * Cow; 10.  cout << 1.0 / 4.0; 13.  char A = 'B', B = 'A';      cout << "A" << A << "B" << B; 11.  float Bear = 1.0, Alligator = 1.0;      Alligator++;      Bear--;      cout << Alligator + Bear; 14.  float A, B = -2.5;      A = B * 2;      A++;      cout << A;