Variable Operations


Now that we've declared variables, we need to be able to assign values to them and operate on them. For the most part, the syntax is the same as Pascal, but with a few differences that will probably haunt you for at least a few chapters of this tutorial. Don't worry, though -- like learning anything, practice makes perfect, and once you've written some small programs, you'll get it down. Here is a list of common operators in C++:

Pascal     C++      Meaning

+          +        Adds two numbers
-          -        Subtracts two numbers
/          /        Divides one number by another
*          *        Multiplies one number by another
MOD        %        Gives you the remainder of division between two numbers
:=         =        Assigns one number to another

The two that will be giving you the most problems are the assignment operator and the equality operator. For instance, if you want to set a variable salsa to 3, you would say:

Mmm..Salsa Pascal:

salsa := 3;
C++:
salsa = 3;

Note that C++ uses "=" to assign values and not ":=", which Pascal uses! While you'll probably come to the conclusion (once you've become a C++ person) that this is actually better, it should be pretty confusing right now. So, let's try making a small program with this knowledge!

void main(void)/ Declare the main function
{
   double a;   /* Declare a double named a */

   a = 5.2;    /* Assign 5.2 to a */
   a = a+2;    / Assign 7.2 to a (5.2 + 2)

   int b;      / Wow! We just declared a variable right in the middle of
               / everything.. Is this really a good idea?
   int B;      /* Remember, C++ is case sensitive! */

   b = B = 10; /* Assign 10 to b and B */
}

Slowly go over the example above. For the most part, you shouldn't have any trouble understanding it. You may have taken a double take on the last statement in the procedure, "b = B = 10;". How can this be? Well, when this program is run, that statement is run right-to-left. First, the statement "B = 10" is executed, which assigns 10 to B. That statement then returns the value 10, leaving only "b = 10", which of course assigns 10 to b. You may have better luck thinking of the whole statement as "b = (B = 10);" instead.

Did you notice that we declared b and B right in the middle of the program? While this may seem really neat at first, it does get confusing. We suggest keeping them at the top of your functions, where a is, in the future.

You may have also been confused by the line "int B;". Didn't you just declare "b"? Remember, C++ is case sensitive. "B" is a completely separate variable from "b". Don't mix up your variables!


Table of Contents

The Big Picture | Comments | Variables | More on Variables
Variable Operations | Making Choices | More on if | Using else
Using switch | The while Loop | The do..while Loop | Constants
The for Loop | More on the for Loop | Exercises