Department of Engineering

IT Services

4. Assignment of variables

Assignment of statements

department imageIt is essential that every variable in a program is given a value explicitly before any attempt is made to use it. It is also very important that the value assigned is of the correct type.

The most common form of statement in a program uses the assignment operator, =, and either an expression or a constant to assign a value to a variable:

    variable = expression;                         
    variable = constant;                         

The symbol of the assignment operator looks like the mathematical equality operator but in C++ its meaning is different. The assignment statement indicates that the value given by the expression on the right hand side of the assignment operator (symbol =) must be stored in the variable named on the left hand side. The assignment operator should be read as ``becomes equal to'' and means that the variable on the left hand side has its value changed to the value of the expression on the right hand side. For the assignment to work successfully, the type of the variable on the left hand side should be the same as the type returned by the expression.

The statement in line 10 of the simple adder program is an example of an assignment statement involving an arithmetic expression.

       total = a + b;

It takes the values of a and b, sums them together and assigns the result to the variable total. As discussed above, variables can be thought of as named boxes into which values can be stored. Whenever the name of a box (i.e. a variable) appears in an expression, it represents the value currently stored in that box. When an assignment statement is executed, a new value is dropped into the box, replacing the old one. Thus, line 10 of the program means "get the value stored in the box named a, add it to the value stored in the box named b and store the result in the box named total".

The assignment statement:

       total = total + 5;

is thus a valid statement since the new value of total becomes the old value of total with 5 added to it. Remember the assignment operator (=) is not the same as the equality operator in mathematics (represented in C++ by the operator ==).

Arithmetic expressions

Expressions can be constructed out of variables, constants, operators and brackets. The commonly used mathematical or arithmetic operators include:

modulus (modulo division)

The definitions of the first four operators are as expected. The modulo division (modulus) operation with an integer is the remainder after division, e.g. 13 modulus 4 (13%4) gives the result 1. Obviously it makes no sense at all to use this operator with float variables and the compiler will issue a warning message if you attempt to do so.

Although addition, subtraction and multiplication are the same for both integers and reals (floating point numbers), division is different. If you write (see later for declaration and initialisation of variables on the same line):

   float a=13.0, b=4.0, result;
   result = a/b;

then a real division is performed and 3.25 is assigned to result. A different result would have been obtained if the variables had been defined as integers:

   int i=13,j=4, result;
   result = i/j;

when result is assigned the integer value 3.

The remainder after integer division can be determined by the modulo division (modulus) operator, %. For example, the value of i%j would be 1.

Precedence and nesting parentheses

The use of parentheses (brackets) is advisable to ensure the correct evaluation of complex expressions. Here are some examples:

4+2*3 equals 10
(4+2)*3 equals 18
-3 * 4 equals -12
4 * -3 equals -12 (but should be avoided)
4 * (-3) equals -12
0.5 (a+b) illegal (missing multiplication operator)
(a+b) / 2 equals the average value of a and b only if they are of type float

The order of execution of mathematical operations is governed by rules of precedence. These are similar to those of algebraic expressions. Parentheses are always evaluated first, followed by multiplication, division and modulus operations. Addition and subtraction are last. The best thing, however, is to use parentheses (brackets) instead of trying to remember the rules.

Initialisation of variables

Variables can be assigned values when they are first defined (called initialisation):

type variable = literal constant;
float ratio = 0.8660254;
int myAge = 19;
char answer = 'y';
bool raining = false;

The terms on the right hand side are called constants.

(Note the ASCII character set is represented by type char. Each character constant is specified by enclosing it between single quotes (to distinguish it from a variable name). Each char variable can only be assigned a single character. These are stored as numeric codes. The initialisation of words and character strings will be discussed later in the section on advanced topics.)

The declaration of a variable and the assignment of its value in the same statement can be used to define variables as they are needed in the program.

   type     variable = expression;
   float   product = factor1*factor2;

The variables in the expression on the right hand side must of course have already been declared and had values assigned to them.

Warning: When declaring and initialising variables in the middle of a program, the variable exists (i.e. memory is assigned to store values of the variable) up to the first right brace that is encountered, excluding any intermediate nested braces, { }. For the simple programs described here, this will usually be the closing brace mark of the program. However we will see later that brace marks can be introduced in many parts of the program to make compound statements.

Expressions with mixed variable types

At a low level, a computer is not able to perform an arithmetic operation on two different data types of data. In general, only variables and constants of the same type, should be combined in an expression. The compiler has strict type checking rules to check for this.

In cases where mixed numeric types appear in an expression, the compiler replaces all variables with copies of the highest precision type. It promotes them so that in an expression with integers and float variables, the integer is automatically converted to the equivalent floating point number for the purpose of the calculation only. The value of the integer is not changed in memory. Hence, the following is legal:

   int i=13;
   float x=1.5;
   x = (x * i) + 23;

since the values of i and 23 are automatically converted to floating point numbers and the result is assigned to the float variable x.

However the expression:

   int i=13,j=4;
   float result;
   result = i/j;

is evaluated by integer division and therefore produces the incorrect assignment of 3.0 for the value of result. You should try and avoid expressions of this type but occasionally you will need to compute a fraction from integer numbers. In these cases the compiler needs to be told specifically to convert the variables on the right-hand side of the assignment operator to type float. This is done by casting.

In the C++ language this is done by using the construction:
   static_cast< type > expression
(In the C language this is done by a different construction using: (type) expression.)

For example:

   int count=3, N=100;
   float fraction;
   fraction  = static_cast<float>(count)/N;

converts (casts) the value stored in the integer variable count into a floating point number, 3.0. The integer N is then promoted into a floating point number to give a floating point result.

Declaration and initialisation of symbolic constants

Like variables, symbolic constants have types and names. A constant is declared and initialised in a similar way to variables but with a specific instruction to the compiler that the value cannot be changed by the program. The values of constants must always be assigned when they are created.

   const   type      constant-name = literal constant;
   const   float    Pi = 3.14159265;
   const   int      MAX = 10000;

The use of constants helps programmers avoid inadvertent alterations of information that should never be changed. The use of appropriate constant names instead of using the numbers also helps to make programs more readable.

Back to top