More on Variables


One thing that's different in C++ is how you declare arrays. You probably remember that this is how it's done in Pascal:

somearray : array[1..10] of integer;

C++ makes it easier to create arrays - to create the same array as shown above, you simply say:

int somearray[10];

Wasn't that easy? One big difference is that, unlike Pascal, C++ requires that all of your arrays start at 0. So, if we wanted to access element 5 of our array, we'd say:

somearray[4];

Confused? Remember that we're starting the array at 0. The first element is "somearray[0]", then the second is "somearray[1]", and so on. This may take some getting used to; while you're getting started, you can just subtract 1 mentally when you're using arrays. "Let's see, the fifth element, that's somearray[4]"

That may feel kind of silly, but hopefully what we're about to say will make up for it. In C++, variables can be declared nearly anywhere inside a program!

What does this mean? Well, consider this code:

void main(void)   /  In Pascal: "procedure main;"
{                 /  In Pascal: "begin"
   int a;         /  In Pascal: "  a: integer;"
   int b;         /  In Pascal: "  b: integer;"
}                 /  In Pascal: "end"

The variables are being declared right in the middle of a program! That's right -- you can say "int b;" anywhere inside that block! Because there's no special section where you declare variables in C++, you can forget about the "var" keyword you used in Pascal to say you wanted to declare 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