next up previous
Next: Priority of Operators Up: Introduction to C++ Programming Previous: Exercises


The Assignment statement

The main statement in C++ for carrying out computation and assigning values to variables is the assignment statement. For example the following assignment statement:

average = (a + b)/2;
assigns half the sum of a and b to the variable average. The general form of an assignment statement is:
result = expression ;
The expression is evaluated and then the value is assigned to the variable result. It is important to note that the value assigned to result must be of the same type as result.

The expression can be a single variable, a single constant or involve variables and constants combined by the arithmetic operators listed below. Rounded brackets () may also be used in matched pairs in expressions to indicate the order of evaluation.

+ addition
- subtraction
* multiplication
/ division
% remainder after division (modulus)
For example
i = 3;
sum = 0.0;
perimeter = 2.0 * (length + breadth);
ratio = (a + b)/(c + d);

The type of the operands of an arithmetic operator is important. The following rules apply:

The last rule means that it is quite easy to lose accuracy in an assignment statement. As already noted the type of the value assigned must be the same type as the variable to which it is assigned. Hence in the following example in which i is a variable of type int

i = 3.5;
the compiler will insert code to convert the value 3.5 to an integer before carrying out the assignment. Hence the value 3 will be assigned to the variable i. The compiler will normally truncate float values to the integer value which is nearer to zero. Rounding to the nearest integer is not carried out.

A similar problem arises with the division operator. Consider the following rule:

For example the statement
i = 1/7;
will assign the value zero to the integer variable i. Note that if the quotient of two integers is assigned to a float then the same loss of accuracy still occurs. Even if i in the above assignment was a variable of type float 1/7 would still be evaluated as an integer divided by an integer giving zero, which would then be converted to the equivalent float value, i.e. 0.0, before being assigned to the float variable i.

The modulus operator % between two positive integer variables gives the remainder when the first is divided by the second. Thus 34 % 10 gives 4 as the result. However if either operand is negative then there are ambiguities since it is not well-defined in C++ what should happen in this case. For example 10 % -7 could be interpreted as 3 or -4. Hence it is best to avoid this situation. All that C++ guarantees is that

i % j = i - (i / j) * j



Subsections
next up previous
Next: Priority of Operators Up: Introduction to C++ Programming Previous: Exercises
Peter JB King
1999-08-31