4A. Variables

A variable is a place where a program can store a value. There are a few kinds of variables, the simplest being a variable that has a name. That is the only kind of variable that we will use until we get into more detail on a computer's memory.

Like values, every variable has a type; a variable of type T can only hold a value of type T.


Variable names

A variable name must begin with a letter and can contain letters, digits and underscores. For example, my_size, mySize and mysize1 are (different) variable names.

There are some variable names that you should avoid: o, O and l. The first two are easily confused with 0 and the third is easily confused with 1.


Declaring a variable

In most typed languages, including C++, before you use a variable you must declare it and say what its type is. To declare a variable called size  of type int in C++, write

  int size;
A variable declaration always starts with a type, and it can occur wherever you can write a statement.

You can declare several variables in a single declaration by separating their names by commas. For example,

  double x,y,z;
declares variables x, y and z of type double.