Monday, March 26, 2012

Branching Statements (if, else, switch) in C++

the if statement

The first type of branching statement we will look at is the if statement. An if statement has the form:
if (condition)
{
   // code to execute if condition is true
}
else 
{
   // code to execute if condition is false
}
In an if statement, condition is a value or an expression that is used to determine which code block is executed, and the curly braces act as "begin" and "end" markers. Here is a full C++ program as an example:
//include this file for cout
#include <iostream.h>

int main() {
  // define two integers
  int x = 3;
  int y = 4;

  //print out a message telling which is bigger
  if (x > y) {
    cout << "x is bigger than y" << endl;
  }
  else {
    cout << "x is smaller than y" << endl;
  }
  return 0;
}
In this case condition is equal to "(x > y)" which is equal to "(3 > 4)" which is a false statement. So the code within the else clause will be executed. The output of this program will be:
x is smaller than y
If instead the value for x was 6 and the value for y was 2, then condition would be "(6 > 2)" which is a true statement and the output of the program would be:
x is bigger than y

the switch statement

The next branching statement is called a switch statement. A switch statement is used in place of many if statements.
Let's consider the following case: Joel is writing a program that figures interest on money that is held in a bank. The amount of interest that money earns in this bank depends on which type of account the money is in. There are 6 different types of accounts and they earn interest as follows:
account type interest earned
personal financial 2.3%
personal homeowner 2.6%
personal gold 2.9%
small business 3.3%
big business 3.5%
gold business 3.8%
One way for Joel to write this program is as follows: (assuming also that Joel has assigned numbers to the account types starting with personal financial and ending with gold business.)
// declare a variable to keep track of the interest
float interest = 0.0;

// decide which interest rate to use.
if (account_type == 1){
  interest = 2.3;
  }
else {
     if (account_type == 2) {
       interest = 2.6;
       }
     else {
          if (account_type == 3){
            interest = 2.9;
            }
          else {
               if (account_type == 4){
                 interest = 3.3;
                 }
               else {
                    if (account_type == 5){
                      interest = 3.5;
                      }
                    else {
                         // account type must be 6
                           interest = 3.8;
                         }
                    }
               }
          }
     }
That code is hard to read and hard to understand. There is an easier way to write this, using the switch statement. The preceding chunk of code could be written as follows:
switch (account_value){
  case 1:
    interest = 2.3;
    break;
  case 2:
    interest = 2.6;
    break;
  case 3:
    interest = 2.9;
    break;
  case 4:
    interest = 3.3;
    break;
  case 5:
    interest = 3.5;
    break;
  case 6:
    interest = 3.8;
    break;
  default:
    interest = 0.0;
}
The switch statement allows a programmer to compound a group of if statements, provided that the condition being tested is an integer. The switch statement has the form:
 
switch(integer_val){
   case val_1:
      // code to execute if integer_val is val_1
      break;
    ...
   case val_n:
      // code to execute if integer_val is val_n
      break;
   default:
      // code to execute if integer_val is none of the above
}
The default clause is optional, but it is good programming practice to use it. The default clause is executed if none of the other clauses have been executed. For example, if my code looked like:
switch (place) {
   case 1:
      cout << "we're first" << endl;
 break;
   case 2:
      cout << "we're second" << endl;
 break;
   default:
 cout << "we're not first or second" << endl;
}
This switch statement will write "we're first" if the variable place is equal to 1, it will write "we're second" if place is equal to 2, and will write "we're not first or second" if place is any other value.
The break keyword means "jump out of the switch statement, and do not execute any more code." To show how this works, examine the following piece of code:
int value = 0;
switch(input){
  case 1:
    value+=4;
  case 2:
    value+=3;
  case 3: 
    value+=2;
  default:
    value++;
}
If input is 1 then 4 will be added to value. Since there is no break statement, the program will go on to the next line of code which adds 3, then the line of code that adds 2, and then the line of code that adds 1. So value will be set to 10! The code that was intended was probably:
int value = 0;
switch(input){
  case 1:
    value+=4;
    break;
  case 2:
    value+=3;
    break;
  case 3: 
    value+=2;
    break;
  default:
    value++;
}
This feature of switch statements can sometimes be used to a programmers' advantage. In the example with the different types of bank accounts, say that the interest earned was a follows:
account type interest earned
personal financial 2.3%
personal homeowner 2.6%
personal gold 2.9%
small business 2.6%
big business 2.9%
gold business 3.0%
Now, the code for this could be written as:
switch (account_value){
  case 1:
    interest = 2.3;
    break;
  case 2:
  case 4:
    interest = 2.6;
    break;
  case 3:
  case 5:
    interest = 2.9;
    break;
  case 6:
    interest = 3.8;
    break;
  default:
    interest = 0.0;
}

What is a Control Statement in C++

The flow of control

When a programmer is crafting a program, it is good practice to break the program down into pieces that can be thought of independently. Once the program has been completed, we can think of its execution as being a series of these pieces that work together in a certain sequence. These pieces then pass the control of the program between each other. While one piece has the control, the other pieces are inactive. This is known as the flow of control in a program. If our program had three parts, called Start, Middle, and End, the flow of control could look like:
[flow of control diagram]

control statements

Control Statements, then, are ways for a programmer to control what pieces of the program are to be executed at certain times. The syntax of Control statements are very similar to regular english, and are very similar to choices that we make every day. There are two basic types of control statements: branching statements and loops.

branching statements

We will first look at branching statements. Let's say Julien is shopping at a mall and he finds a CD that he wants to buy. Julien then checks his pocket to see if he has enough money to pay for the CD. When he pulls his money out of his pocket Julian may be thinking: "if I have more money than the price of the CD then I will buy the CD." In pseudocode that thought could be translated into:
if (my_money > cost_of_CD) then
 buy_CD
else
 get_a_job
end if;
Note that the pseudocode statement end if means "end the previous if statement." This is to make it clear what statements are inside the if statement and what statements are outside of the if statement.
Depending on a certain condition a certain series of events will be executed. Another type of branching statement is called a switch statement. A switch statement is just a shorter way of writing a lot of if statements. Switch statements will be explained in more detail in the next subsection.

nesting control statements

In the preceding situation, if Julien doesn't have enough money, before going out to get a job, he could look for a friend to borrow the money from. Now the pseudocode for this could be:
if (my_money > cost_of_CD) then
 buy_CD
else
 if (see_a_friend) then
  borrow_money
 else
  get_a_job
 end if;
end if;
Now there is one control statement that is inside of another control statement. This is known as nesting.

loops

Let's pretend now that Julien was buying a house instead of a CD. If Julien wanted to buy the house without taking a loan from the bank, he would have to wait until he had enough money to buy the house. The pseudocode for this could be:
if (my_money > cost_of_house) then
 buy_house
end if;
But this means that Julien would only check once if he had enough money to buy the house. What we want to describe is the fact that Julien needs to keep waiting until he has enough money to buy the house.
while (my_money < cost_of_house) 
 work_more
end while;
buy_house;
This is a loop statement. Another loop statement is the for command. Let's say Julien wanted to add up how much money he would make over the next year. Let's say Julien is paid $500 twice each month. The pseudocode to figure this out could be:
int total=0;
for x = 1 to 24
 total = total + 500
next x;
output total;
A for statement execute a specified number of times. In this instance it executes 24 times (12 months * 2 pay periods per month). In this example, it would actually be easier to write this code as:
total = 24 * 500;
output total;
But, what if Julien earns interest on any money that he saves? Now a for statement will be a handy tool. Let's decide that Julien spends $400 a month on rent, $75 a month on food, and $100 a month on other expenses. Let's also assume that Julien earns 2% per month on any money that he saves. Now our pseudocode could look like:
int monthly_expenses= 400 + 75 + 100;
int monthly_income = 1000;
float interest_rate = .02

// compute the amount Julien will have saved after one year
int total = 0;
int interest_earned =0;
for x = 1 to 12
 interest_earned = total * interest_rate;
 total = total + interest_earned + monthly_income - monthly_expenses
next x;

// display the value
 output  total;
Control statements allow a programmer to craft a program so that certain parts of code execute multiple times, or not at all based on the current state of the program. Control statements are the most basic form of logical control within a program.

Operator Precedence in C++

So far, we've seen a number of different operators. Here's a summary of the operators we've covered so far:
Boolean operators &&, ||, !
Arithmetic operators +, -, *, /, %
Equality operators <, >, ==, <=, >=, !=
Assignment operators =, +=, -=, *=, /=, %=

What is operator precedence?

Operator precedence refers to the order in which operators get used. An operator with high precedence will get used before an operator with lower precedence. Here's an example:
  int result = 4 + 5 * 6 + 2;
What will be the value of result? The answer depends on the precedence of the operators. In C++, the multiplication operator (*) has higher precedence than the addition operator (+). What that means is, the multiplication 5 * 6 will take place before either of the additions, so your expression will resolve to 4 + 30 + 2 , so result will store the value 36. Since C++ doesn't really care about whitespace, the same thing would be true if you had written:
  int result = 4+5 * 6+2;
The result would still be 36. Maybe you wanted to take the sum 4 + 5 and multiply it by the sum 6 + 2 for a result of 72? Just as in math class, add parentheses. You can write:
  int result = (4 + 5) * (6 + 2);

Operator precedence in C++

Operator precedence in C++ is incredibly easy! Don't let anyone tell you otherwise! Here's the trick: if you don't know the order of precedence, or you're not sure, add parentheses! Don't even bother looking it up. We can guarantee that it will be faster for you to add parentheses than to look it up in this tutorial or in a C++ book. Adding parentheses has another obvious benefit - it makes your code much easier to read. Chances are, if you are uncertain about the order of precedence, anyone reading your code will have the same uncertainty.
That having been said, here's the order of operator precedence. In general, the order is what you would think it is - that is, you can safely say
  int x = 4 + 3;
and it will correctly add 4 and 3 before assigning to x. Our advice is to read this table once and then never refer to it again.
Operator precedence
operators have the same precedence as other operators in their group, and higher precedence than operators in lower groups
operator name
! boolean not

* multiplication
/ division
% mod

+ addition
- subtraction

< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to

== is equal to
!= is not equal to

&& boolean and

|| boolean or

= assignment
*= multiply and assign
/= divide and assign
%= mod and assign
+= add and assign
-= subtract and assign

Operators in C++ - Booleans: True and False, Boolean operators in C++, Arithmetic operators in C++, Equality operators in C++ , Assignment operators in C++

Booleans: True and False

Before talking about operators, we'll take a quick aside into booleans, since we'll need to know what a boolean is before discussing operators. A boolean value is one that can be either true or false. No other values are allowed. Booleans and boolean operations are at the heart of programming. Many times in a program, you'll want to do one thing if a certain condition is true, and a different thing if the condition is false. For example, when processing a series of checkboxes, you may want to take an action only if a box is checked, and do nothing otherwise. That's when you'll want to use a boolean.
Most programming languages have a type for booleans, usually called "boolean" or "bool". Some C++ compilers recognize the type bool, others do not. For now, assume that your compiler supports the bool type. We'll discuss what to do if your compiler doesn't, in a moment.
In order to use boolean logic to your advantage, you need to learn about the three basic boolean operations. They are called and, or, and not. Each operation takes either one or two boolean inputs, and returns a boolean output. They are often represented by symbols known as "gates", shown below.
[the AND gate symbol]
and
The "and" operation takes two inputs and produces one output. If both inputs are true, the output is true; in all other cases, the output is false. It can be interpreted as follows: "I will return true if input 1 and input 2 are true."
[the OR gate symbol]
or
The "or" operation takes two inputs and produces one output. If either of the inputs are true, the output is true; otherwise (i.e., if neither input is true), the output is false. It can be interpreted as follows: "I will return true if either input 1 or input 2 is true."
[the NOT gate symbol]
not
The "not" operation takes one input and produces one output. If the input is true, the output is false. If the input is false, the output is true. In other words, the "not" operation takes the input and returns its opposite.

Boolean operators in C++

There are operators in C++ which behave just as the boolean gates shown above! We'll show you an example of how to use each one.

and: &&

The "and" operator is used by placing the "and" symbol, &&, in between two boolean values.
  //suppose that Fran is tired
  bool franIsTired = true;

  //but Fran doesn't have to wake up early
  bool franMustWakeUpEarly = false;

  //will Fran go to sleep now?
  bool bedTime = franIsTired && franMustWakeUpEarly;
What does this chunk of code do? It initializes two variables, franIsTired and franMustWakeUpEarly, to true and false, respectively. Then, in the third line of code (not including comments!), we determine that Fran will go to sleep if and only if the "and" operation is true -- that is, if both inputs to the "and" operation are true. In this case, the first input is true and the second input is false. Since "and" requires both inputs to be true in order for the output to be true, but one of the inputs is false, the output will be false. So, the variable bedTime will store the value false. Also, take note that the variable names used here are lengthy. How you decide to program is up to you, but often times it's better to have lengthier variable names that are readable, rather than short, obfuscated variable names like "i" or "zz". (The names in this example may have gone overboard, though.)

or: ||

The "or" operator is used by placing the "or" symbol, ||, in between two boolean values.
  //suppose that Graham is tired
  bool grahamIsTired = true;

  //but Graham doesn't have to wake up early
  bool grahamMustWakeUpEarly = false;

  //will Graham go to sleep now?
  bool bedTime = grahamIsTired || grahamMustWakeUpEarly;
This example is very similar to the example involving Fran, except notice the key difference: whether or not Graham goes to sleep is determined differently. Graham will go to sleep if he is tired or if he needs to wake up early. Whereas Fran would go to sleep only if both conditions were true, Graham will go to sleep if either condition (or both) is true. Therefore, the value of bedTime is true.

not: !

The "not" operator is used by placing the "not" symbol, !, before a boolean value.
  //suppose that Julian stayed up late
  bool julianStayedUpLate = true;

  //will Julian be peppy tomorrow?
  bool julianIsPeppy = !julianStayedUpLate;
This example illustrates the "not" operator. At the end of this block of code, the variable julianIsPeppy will take on the opposite value of julianStayedUpLate. If julianStayedUpLate were false, then julianIsPeppy would be true. In this case, the opposite is true, so julianIsPeppy gets a value of false. It is perfectly legal in C++ to use boolean operators on variables which are not booleans. In C++, "0" is false and any non-zero value is true. Let's look at a contrived example.
  int hours = 4;
  int minutes = 21;
  int seconds = 0;

  bool timeIsTrue = hours && minutes && seconds;
Since hours evaluates to true, and since minutes evaluates to true, and since seconds evaluates to false, the entire expression hours && minutes && seconds evaluates to false.

Arithmetic operators in C++

In addition to the boolean operators, C++ has a number of arithmetic operators. Here they are:
Arithmetic operators
name symbol sample usage
addition + int sum = 4 + 7
subtraction - float difference = 18.55 - 14.21
multiplication * float product = 5 * 3.5
division / int quotient = 14 / 3
modulo ("mod") % int remainder = 10 % 6
They all probably look familiar with the exception of mod (%). The mod is simply the remainder produced by dividing two integers. In the example shown in the table above, if we treat 10 / 6 as an integer divison, the quotient is 1 (rather than 1.666) and the remainder is 4. Hence, the variable remainder will get the value 4.

Equality operators in C++

You are undoubtedly familiar with equality operators, even if you don't know it. An equality operator is one that tests a condition such as "is less than", "is greater than", and "is equal to". You will find it useful to be able to compare two numbers using expressions like "x is less than y".
Let's say you are writing software for a bank ATM (automated teller machine). A customer makes a request for a certain amount of cash, and your responsibility is to determine if they should be allowed to withdraw that amount. You could decide to use the following algorithm: "if the amount requested is less than the account balance, that amount should be withdrawn; otherwise, the customer should be notified and no money should be withdrawn." Makes sense, right? So, the next step is coming up with some pseudo-code. Once you have pseudo-code, writing the C++ code will be easy.
Pseudo-code for the ATM problem might look like this:
  if the amount requested < account balance then
    withdraw the amount requested
  otherwise
    withdraw nothing and notify the customer
Now that we have pseudo-code, writing the C++ code is as simple as "translating" your pseudo-code into C++. In this case, it's easy:
  if (amountRequested < accountBalance) {
    withdraw(amountRequested);
  }
  else {
    withdraw(0);
    notifyCustomer();   
  }
You'll notice some new syntax in this example, but don't worry about it too much. Pay close attention to the very first line, which checks to make sure that the amount requested is less than the account balance. The way it works is, if the expression between parentheses (()) evaluates to true, then the first block of code will be read. That is, the code inside the first set of curly braces ({}) will be executed. If the expression in parentheses evaluates to false, on the other hand, then the second block of code (the code following the word else) will be read. In this case, the first block of code withdraws the amount requested by the customer, while the second block of code withdraws nothing, and notifies the customer. That wasn't so hard! All we did was take the original English description of how we would solve the problem, write some pseudo-code for the English description, and translate the pseudo-code into C++.
Once you know how to use one equality operator, you know how to use all of them. They all work the same way: they take the expressions on either side of them, and either return true or false. Here they are:
Equality operators
name symbol sample usage result
is less than < bool result = (4 < 7) true
is greater than > bool result = (3.1 > 3.1) false
is equal to == bool result = (11 == 8) false
is less than or equal to <= bool result = (41.1 <= 42) true
is greater than or equal to >= bool result = (41.1 >= 42) false
is not equal to != bool result = (12 != 12) false

Assignment operators in C++

Believe it or not, you've already been using assignment operators! Probably the most common assignment operator is the equals sign (=). It is called "assignment" because you are "assigning" a variable to a value. This operator takes the expression on its right-hand-side and places it into the variable on its left-hand-side. So, when you write x = 5, the operator takes the expression on the right, 5, and stores it in the variable on the left, x.
Remember how the equality operators, like < and !=, returned a value that indicated the result? In that case, the return value was either true or false. In fact, almost every expression in C++ returns something! You don't always have to use the return value, though -- it's completely up to you. In the case of the assignment operators, the return value is simply the value that it stored in the variable on the left-hand-side.
Sometimes your code will use the return value to do something useful. In the ATM example, one line of code was executed if the condition was true (that is, if the equality operator returned true). Two different lines were executed if the condition was false.
Other times, you'll completely ignore the return value, because you're not interested in it. Take a look at the following code:
  int x;
  int y;
  x = 5;
  y = 9;
  cout << "The value of x is " << x << endl;
  cout << "The value of y is " << y << endl;
  int sum;
  sum = x + y;
  cout << "The sum of x and y is " << sum << endl;
This chunk of code shows why you might want to throw away the return value of an operator. Look at the third line, x = 5. We're using the assignment operator here to place the value 5 in the variable x. Since the expression x = 5 returns a value, and we're not using it, then you could say we are ignoring the return value. However, note that a few of lines down, we are very interested in the return value of an operator. The addition operator in the expression x + y returns the sum of its left-hand-side and right-hand-side. That's how we are able to assign a value to sum. You can think of it as sum = (x + y), since that's what it's really doing. Operator precedence is covered on the next page.
The other assignment operators are all based on the equals sign, so make sure you understand that before going on. Here's another assignment operator: +=. How does it work? You might guess that it has something to do with addition, and something to do with assignment. You'd be absolutely right! The += operator takes the variable on its left-hand-side and adds the expression on its right-hand-side. Whenever you see a statement that looks like the following:
  myVar += something;
it is identical to saying the following:
  myVar = myVar + something;
That's exactly what it's doing! It's simply a shortcut. The other common assignment operators are -=, *=, /=, and %=. They all function just like the += operator, except instead of adding the value on the right-hand-side, they subtract, or multiply, or divide, or "mod" it.
Just as the simple assignment operator = returns the value that it stored, all of the assignment operators return the value stored in the variable on the left-hand-side. Here's an example of how you might take advantage of this return value. It's not used terribly often, but it can sometimes be useful.
  //these four variables represent the sides of a rectangle
  int left;
  int top;
  int right;
  int bottom;

  //make it a square whose sides are 4
  left = top = right = bottom = 4;
All this code does is store the value in each of the four variables left, top, right, and bottom. How does it work? It starts on the far right-hand side. It sees bottom = 4. So it places the value 4 in the variable bottom, and returns the value it stored in bottom (which is 4). Since bottom = 4 evaluates to 4, the variable right will also get the value 4, which means top will also get 4, which means left will also get 4. Phew! Of course, this code could have just as easily been written
  //these four variables represent the sides of a rectangle
  int left;
  int top;
  int right;
  int bottom;

  //make it a square whose sides are 4
  left = 4;
  top = 4;
  right = 4;
  bottom = 4;
and it would have done the exact same thing. The first way is more compact, and you're more likely to see it written the first way. But both ways are equally correct, so use whichever you prefer.

Casting of Variables in C++

How Do Computers Store Variables?

In any programming language, and especially in C++, it's important to have at least a cursory understanding of what the computer is doing "behind the scenes". Since we're talking about variables in this chapter, it's important to understand how a computer stores the information in variables.

More Variable Types

For reasons not explained here, variables can only store finite numbers. Suppose that the size of a particular data type, that we'll call a gorb, is 1 byte. That means that gorbs can only represent 28*1 = 28 = 256 distinct values. So, gorbs might be able to store only the numbers between 0 and 255 (inclusive). Any number that you tried to store in a gorb which was smaller than 0, or larger than 255, would not be stored correctly; it would be stored as one of the values between 0 and 255. However, maybe you want to be able to store positive and negative numbers in gorbs, in which case you'd only be able to store 128 negative numbers and 128 positive numbers. Since we need to be able to store 0 also, you might decide that the range of values for a gorb is -128 to 127.
We've already learned about two different data types (not including "gorbs"!): int and float. What are the sizes of these data types, and what are the limits on the kinds of values that they can store? We just saw that a data type whose size is 1 byte can store 256 distinct values. Data types of size 2 bytes can store 28*2 = 216 = 65536 different values. Using the same formula, we determine that data types of size 4 bytes can store 28*4 = 232 = 4,294,967,296.
Unfortunately, the size of data types like int and float are not standard across all systems. The size of an int depends on your operating system and your hardware. Here are some typical values for ints and floats, along with some other important data types.
type typical size description

short 2 bytes stores a short (i.e., small) integer
int 4 bytes stores an integer
long 4 bytes stores a long (i.e., large) integer
float 4 bytes stores a floating-point number
double 8 bytes stores a "double-precision" floating-point number
A more complete listing of variable types can be found in Appendix B.

When to Cast

Casting a variable is a complicated name for a simple concept. When you cast a variable from one type to another, all you are doing is telling the computer to use a different type to store the variable. Why would you need (or want) to do this? Let's say you declared a variable of type short. In most cases, that would mean that the largest positive value you could store would be 32,767. But somewhere in your program, you realize that you're going to have to do a calculation which could increase the value over this maximum. Perhaps you are computing very large Pythagorean triplets. To calculate the value of c (the hypotenuse), you need to take the square root of the quantity a2 + b2. But what if a or b is very large? Then squaring that number will make it much, much larger -- and if the value becomes bigger than 32,767 your values will not be what you expected (if you had used a short to store a or b. Remember, a short can only store the values between -32,768 and +32,767, so if you try to store a number out of this range, your data will be incorrect!
So, the solution is to cast. We can cast the numbers to a larger data type, such as an int or a long, for the purposes of the calculation -- and then we can cast them back to a short when we are done, since the final value for c will probably be small enough to be stored in a short.
This is a somewhat trivial example, since in this case you could store the numbers in ints or longs from the beginning and not worry about it! A more useful example might be if you have a number which represents an average. You'll probably want to represent the number with a floating-point type like a float or a double so that it is accurate while you are computing it (otherwise you'd only be able to store a value like "26" instead of "26.3141885"). Let's say that you want to display the value in a table, yet the table would look cluttered if you displayed "26.3141885", so you decide to simply display the integer portion, 26. You can cast the float to an int and then display the int in the table -- since ints can't store floating-point numbers, the decimal portion of "26.3141885" will be truncated and you will be left with "26".

How to Cast

Casting in C++ is easy. Let's say that you have a float storing a number like "26.3141885", and you want to have an int storing the integer portion instead. Here's how to do it:
int GetAverage() {

// assume that regularAverage and specialAverage store two floats
  float totalAverage = regularAverage + specialAverage;

// cast totalAverage to an int
  int truncatedAverage = (int) totalAverage;

// return the truncated value
  return truncatedAverage;
}
There's a little bit of syntax that you haven't seen before, but the key part to notice is the line of code that reads int truncatedAverage = (int) totalAverage. What we're doing here is taking a float, totalAverage, which stores some kind of decimal number (like 82.41832), and getting rid of the ".41832" part by casting it to an int. That works because the int is only capable of storing integers, so it simply stores the integer portion of totalAverage.

Variable Types and Declaring Variables

Variable Types

A variable type is a description of the kind of information a variable will store. Programming languages vary regarding how strict they require you to be when declaring a variable's type. Some languages, like Perl, do not require you to announce the type of a variable. Other languages require you to declare some variables as numbers and others as text-strings, for example. C++, a strongly-typed language, requires you to be even more specific than that. Instead of declaring a variable as a number, you must say whether it will store integers or decimals. In C++, the type of an integer is int and the type of a decimal is float (floating-point number).

Declaring Variables

Declaring a variable in C++ is simple. Let's say you want to declare a variable of type int called myAge. That is to say, the variable myAge will store an integer. In C++, this is written:
int myAge;
All this does is tell the computer that you plan to use an integer, and that the integer's name is myAge. In some languages, variables are initialized to 0 - that is, a variable's initial value will be 0. This is not true of C++! Sometimes your variables will be initialized to 0, but sometimes they will be initialized with garbage. As you might anticipate, this can cause some nasty bugs. Let's take a look at another sample program.
#include <iostream.h>

int main() {
  int myAge;
  cout << "My age is " << myAge << endl;
  return 0;
}
You might expect the program to output "My age is 0". In fact, the output of this program is unreliable. On one system you may get output of "My age is 11"; another system may output "My age is 0"; yet another system may output "My age is 3145". That's what it means to have a variable initialized with garbage. It is always a good idea to initialize your variables with some value. If you don't know what a variable's initial value should be, initialize it to 0. Initializing a variable is easy. Let's fix the above program so that it always outputs "My age is 22". The first line of the main function initializes myAge by assigning it a value immediately.
#include <iostream.h>

int main() {
  int myAge = 22;
  cout << "My age is " << myAge << endl;
  return 0;
}
That's all there is to it! By the way, the equals sign ("=") is called an operator and will be covered later in Section 3.

What is a Variable?

A variable is a place to store a piece of information. Just as you might store a friend's phone number in your own memory, you can store this information in a computer's memory. Variables are your way of accessing your computer's memory.
Of course, your memory changes over time. Your friend moves across country and has a new phone number, and your friend's new phone number will replace the old one in your memory. Over time, as you acquire new friends, your memory will keep changing to store different pieces of information. Likewise, a computer's memory can change over time, if you tell it to. Since variables are your access point to your computer's memory, it makes sense that you'd be able to change the information in a computer's memory; otherwise, they wouldn't be called variables (they'd be called statics).
Why should you care about variables? Variables are the essence of any computer program! Without variables, computers would be useless. Imagine a program which asks the user for two numbers and adds them together, and prints the result.
# AddTwoNumbers
Enter the first number: 2
Enter the second number: 5
The sum of 2 and 5 is 7.
# 
Sounds simple, right? But let's do a little role-playing to see what the computer has to do to execute this program. Instead of this interaction between a person and a computer, let's imagine the same kind of conversation between two people, Sol and Frank.
Sol: Hey Frank, I just learned how to add two numbers together.
Frank: Cool!
Sol: Give me the first number.
Frank: 2.
Sol: Ok, and give me the second number.
Frank: 5.
Sol: Ok, here's the answer: 2 + 5 = 7.
Frank: Sheesh! This guy is unbelievable!
After Frank says "2", Sol has to store that number in his memory somewhere. It may be stored in short-term memory, but he has to store it somewhere before Frank gives him the second number. Even if Frank were to give him two numbers in the same sentence, Sol would have to store the numbers somewhere in his memory to add them together. In the sample program described above, the computer would most likely store "2" in a variable, then store "5" in a variable, and then calculate the sum by calculating the sum of the numbers store in the two variables.
Although there are similarities between a person's memory and a computer's memory, there are some pretty big differences. In C++, you need to grab a little piece of the computer's memory before you can use it. In other words, you have to tell the computer that you're planning to store a number in a variable before you can actually do it. This is called declaring a variable. To declare a variable, you need to know what kind of information it will store (i.e., will it store a number, or a text-string, or something else) and how you plan to refer to the variable (i.e., the variable's name). C++ imposes fairly strict rules on how you can name your variables:
  • variable names must begin with a letter
  • variable names are "case-sensitive" (i.e., the variable "myNumber" is different from the variable "MYNUMBER" which is different from the variable "mYnUmBeR")
  • variable names can't have spaces
  • variable names can't have special characters (typographic symbols)
What can you name your variables? In general, variable names can be composed of letters, numbers, and underscores (_). However, C++ reserves certain keywords which have special meaning to the language, and you are not allowed to use any of these keywords as variables names. Some examples of C++ keywords are int, for, else, and class. You can, however, use keywords in the middle of a variable name, such as "foreign" or "classical". For a complete list of C++ keywords, please see Appendix B.