Variables
In mathematics, a variable is a letter that represents a value. In programming, the basis of a variable is similar to that of math, but is much more involved. As opposed to math, variables in programming are not restricted to letters, and are usually several characters long. Variables can contain any alphanumeric, but must always begin with a letter. Certain other characters are also allowed, depending on what language you are programming in. In C/C++, an underscore is a valid character in a variable name, and can even be the first character in the variable name.
Every variable that is used in a program must first be initialized. The minimum information required when initialized a variable is the data type and name of the variable. The data type specifies what kind of information the variable will store. This is important for the computer to know, since it must set aside enough system memory to store the data. For instance, in most operating systems, an integer takes up two bytes in memory. When an integer variable is initialized, the computer makes two bytes of memory available to store values associated with that variable. A two byte memory space can contain numbers -32,768 -> +32,767. If a value that is out of the integer range must be stored, the variable is initialized with a different data type that tells the computer to set aside more memory. For instance, a long integer type is four bytes, and can store values over two billion. Besides integers, other types of data can be used, and the computer needs to be instructed as to how much memory to set aside. Floating-point numbers are four bytes. The double data type is eight bytes long, and can store larger numbers than float. Some variables can even define a whole set of values, however this will be discussed in a later lesson. The syntax for initializing a variable in C/C++ is
data_type variable_name;
For instance, the following statement initializes a variable called minimum of type int.
int minimum;
Variables can also be defined in the same statement as they are initialized.
int minimum = 5;
A standard variable can always be changed at any point in the program.
minimum = 5;
Remember, in order to give a variable a value, it must first be initialized.
Variables with special conditions can be defined as well. A value can be made a constant by using 'const' when initializing it. The value of a constant cannot be changed (the compiler will signal an error if an attempt is made to change a constant's value), and must therefore be defined in the same statement as it is initialized.
const int minimum = 20;
Other types of variables can also be declared, however, they are not important in order to understand the implementation of the data structures presented.