Consider the following code:
void main () { int result; result = 10 * 10; cout << result << endl; }In this program we want to store the square of 10 so that it can be used later. The first line (int result;) is the declaration of a variable. When a variable is declared it will have a random value as its initial value. You can given it a value at a later stage. In the example above result is declared and is given a value which is the square of 10.
To store a value in a variable we use the assignment (=) operator. The expression to the right of the = sign is evaluated and the result of it is stored in the variable name on the left of the = sign. You can build up complex expressions by using combinations of arithmetic operators taking into account the order of precedence of operators.
For example:
result = (2 + (6 * 4 - 3)) / 10
You can also use other variables in arithmetic expressions. Consider the code below.
void main () { int result; int num; num = 10; result = num * num; cout << result << endl; }Now instead of using the implicit value 10 to calculate the square of 10, we now sotre the value we want to square in a variable called num. To calculate the square of the value we use the variable num. When the computer evaluates the expression when you run the program it will find out what the current value in num is and then multiply it by itself and store the answer in result. Now if we want to calculate the square of another number then all we need to do is change the value we assign to num.
What do you think would happen if you ran the code below:
void main () { int result; result = result + 10; cout << result << endl; }What would be printed to the screen? The answer is: it is undefined. When a variable is declared it will have a random value as its initial value. In the example above the variable result is declared and then the next statement is to add 10 to the current value of result, thinking that result will be zero initially. All it actually will do is add 10 to the random value. This is a very common programming error.
It is good programming practice to always intialise variables to zero or some other known value when they are declared. That way you always know what the initial value of a variable is. You can declare a variable and immediately give it an initial value, as shown in the code below.
void main () { int result = 0; result = result + 10; cout << result << endl; }