|
©1994-2003 Kevin Boone |
| Home Section index K-Zone home | C++ tutorial (under construction) |
|
Variables can store numbers whose values can change It is all very well to specify calculations with pre-defined numbers, like '2' or '3', but what about numbers whose values are not known in advance? For example, suppose the program uses numbers entered by the user? Inputting data will be covered later; this section simply introduces the use of variables. In C/C++ a variable is any piece of data with a name. Variables can contain numbers (various types), text or complex information. A very simple use of variables, to store integer numbers, is demonstrated in the program vars1.cpp. This calculates '4 + 6', but uses variables to store the numbers, rather than directly entering the numbers. The advantage of doing this will become clear later, it if is not now. The first important line in the program is
int i = 4; In this line 'int' means 'integer', i.e., 'i' is to be an integer variable. In this case 'i' is initially set to '4'. 'j' is initially set to '6'. Of course, because these are variables, the program can change these values later if required. You don't have to set a value to a variable when it is created. For example, the variable may be set later in response to user input. In this case, we could have written:
int i; meaning: 'i' is to be an integer variable, but its value is not yet known. The program could later set a particular value to the variable using a line like:
i = 99;
Variables can be used like the data they store
cout << i << " + " << j << " = " << i+j << "\n"; adds the variables 'i' and 'j' and prints the result exactly as if 'i' and 'j' had been pre-defined numbers like '2' or '3'.
Variables can store any type of data that the compiler knows about
float Speed = 30.0; // A standard real number variable char NextCharacter = 'x'; // A single character variable char Message[] = "Press any key..."; // A character string variable As ever, things are a bit more complicated than they appear. For example, real numbers can be stored with various precisions. 'float' defines a variable of standard precision, 'double' is a variable of higher precision, and 'long double' the highest precision available. With a modern compiler on a PC, a 'long double' variable is good for about 20 decimal places. Incidentally, the word 'float' stands for 'floating point', the technique used to represent factional numbers in the computer. For more information about data types and their properties, see the reference section.
Variables must be defined before use
Variables have fixed type |