Forum
101

C++ Level 2

# Operators & Expressions

Introduction

Operators

 Assignment Operators Arithmetic Operators Increment/Decrement Operators

Expressions

 Associativity Precedence & the Order of Evaluation Type Conversions

Extension Work

## Introduction

In C++, how do you assign values to variables, carry out mathematical operations and form expressions? An expression is a combination of operations on variables, constants and literal values and they are fundamental to C++.

This tutorial covers the assignment and mathematical operators, associativity and order of evaluation of expressions and finally, type conversions between different datayptes.

## Operators & Operands

An operator is a symbol that causes the compiler to take an action. Operators act on operands. In C++ there are several different categories of operators. Three of these categories are:-

•   Assignment Operators
•   Arithmetic Operators
•   Increment & Decrement Operators

### Assignment Operators

The assignment operator `(=)` causes the operand on the left side of the assignment operator to have its value changed to the value on the right side of the assignment operator.

The general form of an assignment statement is:

variable = expression

Here is an example:-

`int x = 10;`

Really, the assignment operator `=` does not mean ‘is equal to’ in the algebraic sense. You should imagine it as meaning ‘becomes’ or ‘set’.  Thus, ```x = 10``` means `x` is set to a value of `10`.

Let's also look at the meaning of the terms operator and operand in this example. In the statement ```x = 10```, the operator is `=` and the operands are `x` and `10`

We can modify the value a variable holds at any time later in a program by using the assignment operator again.  Consider the following:-

`int x = 10;`

`x = 5;`

The variable `x` is declared and assigned a value of `10`.  Later, `x` is assigned a new value of `5`. Notice that a particular variable can only keep one value — the current value

Here are some more assignment statements.

`int x;`

`int y;`

`x = 6;`          //assign the literal value of 6 to x

`y = x; `        //assign the value held by the variable x to y

### Arithemetic Operators

The arithmetic operators are listed below.

 Operator Name Example Description `+` addition `x = y + 4;` put the value of y plus 4 into x `-` subtraction `x = y - 4;` put the value of y minus 4 into x ```*  ``` multiplication `x = y * 4`; put the value of y times 4 into x ```/ ``` division `x = y / 4;` put the value of y divide by 4 into x `%` modulo (remainder) ```x = y % 4;``` put the value of the remainder of y divided by 4 into x

You should note that the effect of division in C++ is not always the same as arithmetic division when using integers.

For example:-

`10 / 4` will give the integer result 2

`int x = 10;`

`x / 4` will also give the integer result 2

If any of the operands are real, the result will be real;-

`10.0 / 4` will give the real result 2.25

`int x = 10.0;`

`x / 4` will also give the real result 2.25

Warning: do NOT attempt to divide by zero; this will cause an error.

~Now try the activity~

 Activity A Question 1 Look at the code below. int x = 10, y = 5; x = y + 2;     What is the value of x? Question 3 Look at the code below. int p = 10, q = 5; p =  4 - q;    What is the value of p? Question 2 Look at the code below. int x = 10, y = 5; x = y + 2; y = x + 4; What is the value of y? Question 4 Look at the code below. int p = 10, q = 5; p =  4 - q; q =  4/ p; What is the value of q? Why not check your answers by using code.

The following is another common operation.

`x = x + 2;`   //x is assigned a new value of 8

The variable `x` is re-assigned the value it currently holds added to the number `2`.  In other words - add the number `2` to the value of `x` and re-assign this new number to `x`.  Here are a few more examples of a similar kind.

`x = 6; `

`x = x - 2;`     //x is assigned a new value of 4.  I.e. 6 - 2

`x = x * 2;`     //x is assigned a new value of 8.  I.e. 4 * 2

`x = x / 2; `    //x is assigned a new value of 4.  I.e. 8 / 2

`x = x % 2;`   //x is assigned a new value of 0.  I.e. 4 % 2 leaves a remainder of 0

The table below shows there are shorthand operators for these 5 operations.  Instead of typing:-

`x = x + 2; `

I can type:-

`x += 2; `

...which produces the same result.  A complete list of assignment operators is shown in the table below.

 Operator Name Example Description `=` assignment `x = 10;`    `x = y;` put the value of 10 into x put the value of y into x ```+= ``` assignment with addition `i +=10;` shorthand for i = i+10 `-=` assignment with subtraction `i -=10;` shorthand for i = i-10 `*=` assignment with multiplication `i *=10;` shorthand for i = i*10 `/=` assignment with division `i /=10;` shorthand for i = i/10 `%=` assignment with modulo division ```rem %=10```; shorthand for rem = rem%10

~Now try the activity~

 Activity B Question 1 Look at the code below. int x = 10; x += 2; y *= x; What is the value of x? Question 3 Look at the code below. int p = 10; p -= 2; q /=  p; What is the value of p? Question 5 Look at the code below. int rem = 6 % 4; What is the value of rem? Question 2 Look at the code below. int x = 10, y = 5; x += 2; y *= x; What is the value of y? Question 4 Look at the code below. int p = 10, q = 40; p -= 2; q /=  p; What is the value of q? Question 6 Look at the code below. int rem = 13 % 7; What is the value of rem? Why not check your answers by using code.

### Increment/Decrement Operators

Some time ago a large number of programs were studied and statements of the form...

`int n = 5;`

```n = n + 1;```

...were found to be extremely common.  The `n` on the left-hand side of the `=` is assigned a new value using the current value of `n`, incremented by 1, in this case resulting in 6.  Thus,

`something = something + 1;`

and

`something = something - 1;`

were found to be such a common instructions that many programming languages created a shorthand version of this increment or decrement instruction. The shorthand increment version is written as:-

`something++;`

The shorthand decrement version is written as:

`something--;`

The table below shows the increment/decrement operators.

 Operator Name Example Description `++` increment before `++j;` ```k = ++j;``` increment j by 1 before using increment j by 1 before assigning the value to k `++` increment after ```k = j++;``` increment j by 1 after assigning the value of j to k `--` decrement before `--j;` ```k = --j;``` decrement j by 1 before using decrement j by 1 before assigning the value to k `--` decrement after ```k = j--;``` decrement j by 1 after assigning the value of j to k

We can see from the table that the increment and decrement operators can be positioned before or after a value or variable.  To understand the different results from this positioning let's look at a few examples.

Increment example

`int count = 10;`

`count = count + 1;`  //Increment count by 1. The result is count holds a value of 11

Alternative

`count++;`    //Increment count by 1

Decrement example

`int count = 10;`

`count = count - 1;`  //decrement count by 1.  The result is count holds a value of 9

Alternative

`count--;`    //decrement count by 1

Now, the position of the increment/decrement operators can be important in an expression.

When `++` follows the variable (e.g. `count++`) incrementation happens last.  This is called post-incrementing.   When `++` comes before the variable (e.g. `++count`) incrementation happens first.  This is called pre-incrementing.Post-increment example

`int k = 10, ans;`

`ans = k++;  `

The value of `k` is assigned to ans first.  Then `k` is incremented.  So `ans` now has a value of `10` and `k` has a value of `11`

Pre-increment example

`int k = 10, ans;`

`ans = ++k; `

First `k` is incremented.  Then the value of `k` is assigned to `ans`.  So `ans` now has a value of `11` and `k` has a value of `11`.

The same principles apply to the decrement operator -- only we would call it post-decrementing and pre-decrementing.

~Now try the activity~

 Activity C Question 1 Look at the code below. int ans = 1; count = 2; ans += count++; What is the value of count? Question 3 Look at the code below. int p = 10, q = 5; p = ++q + 3; What is the value of q? Question 5 Look at the code below. int x = 2, y = 5; y  += 3; x *= y--; What is the value of y Question 2 Look at the code below. int ans = 1; count = 2; ans += count++; What is the value of ans? Question 4 Look at the code below. int p = 10, q = 5; p = ++q + 3; What is the value of p? Question 6 Look at the code below. int x = 2, y = 5; y  += 3; x *= y--; What is the value of x? Why not check your answers by using code.

## Expressions

An expression in C++ is a combination of operators and operands (variables, literal values and method calls.)  In the expression

```  a = b + c;```

`a`, `b` and `c` are variables (or operands) and `=` and `+` are operators.  Since an expression can contain an unlimited number of operators in any order, you have to be aware of both operator associativityprecedence and the order of evaluation of expressions.

### Associativity

If all the operators are the same then the rule is simple - all the arithmetic operators associate left to right.  Consider the following:-

`a = b + c + d;`

In calculating the value on the right of the `=` operator, `b` + `c` is calculated first, then `d` is added to the result.  Here are a few more.

`vol  =  length * height * depth;`

`result = x / y / z;`

In the first case, although the expression (```length * height * depth```) is evaluated from left to right you would get the same answer even if you could change this associative order (which you can't).  In the second case you would get an incorrect answer if somehow the associative order could be changed. To see this, consider the correct equivalent of  x / y / z using parenthesis:-

`result = ( x / y)  /  z;`

If you assumed the following was equivalent you would be incorrect.

`result = x / (y  /  z);`

Try giving values to `x`, `y`, `z`.  Say `x = 10`, `y = 5` and `z = 2`.  Then...

`result =  x / y  /  z;`

is equivalent to `(10/5)/2` which is `1`, not `10/(5/2)` which is  `4`

### Precedence & Order of Evaluation

What happens if the operators in an expression are not all the same type, but are a mixture?  The associative rule doesn't apply.  In mathematics, if you write `A+B*C` you would first multiply `B` by `C` and then add `A`.  Thus, the multiplication operator takes precedence over the addition operator.  In fact, the operators `*` and `/` take precedence over `+` and `-`.  The same precedence rules are applied in C++.

Here are some examples...

`3 + 4 * 2` results in 11

```3 - 4 / 2``` results in 1

`3 + 4 * 2 - 5` results in 6

It is often better to use parenthesis to make sure that expressions are evaluated in the order we wish and to make our code clearer.  Parenthesis take the highest precedence.  Any expression in parentheses is evaluated first. Let's re-write the examples above using parentheses.

`3 + ( 4 * 2)` results in 11

`3 - (4 / 2)` results in 1

`3 + (4 * 2) - 5` results in 6

I can force a change in the natural precedence order.  The expression:-

`3 + 4 * 2` results in 11

is equivalent to

`3 + ( 4 * 2)` results in 11

but I could force a change in the precedence order by moving the parentheses:-

`(3  +  4 )* 2`  results in 14

~Now try the activity~

 Activity D Determine the result of each of the following expressions. 6 + 3 * 4 / 2  (6 + 3) * 4 / 2  -5 * 4 - 6 / 2  -5 * (4 - 6) / 2  Why not check your answers by using code.

### Type Conversion

What happens if we have an expression with different data types involved?  e.g.

`float x;`

`int y = 5;`

`x = y;`

What will be the resulting value of `x`?  Will it be `5` or a floating point version of `5`, say `5.0`.

In fact `x` would end up with a floating point version of `5`.  In this case, C++ automatically converts the integer value of `5` to a floating point value of `5.0`.

As we will see, C++ will carry out automatic type conversion in some cases.  If we specifically need to convert values from one type to another we can force a type conversion.

Let's look at automatic conversion and then how to force a type conversion.

### Automatic type conversion

Automatic type conversion means that we can copy a weaker data type to a stronger one, such as an `int` to a `float` and a `float` to a `double` without having to think about it.  C++ automatically does the conversion for us.

Consider:-

`int x = 4;`

`double y;`

`y = x;`

Then `x` would have the value of  `4` but `y` would have the value of `4.0`.   Instead of assigning an integer `4` to `y`, the `4` is converted to a `double` and then assigned to `y` because `y` is expecting to hold a `double` data type and not an integer.

C++ will carry out type conversion automatically for us as long as the conversion is from a weaker type to a stronger type.

 char           short           int           long           float           double Weakest Strongest

However, trying to convert from a stronger to a weaker type, such as...

`int x;`

`double y = 3.2;`

` x = y;`

...would result in a loss of precision because we are trying to get `x`, which was expecting to hold an integer data type to hold a floating point value. In fact `x` has been allocated four bytes of memory but a double requires 8 bytes, so there is only enough room for `x` to hold the number `3` - the first part of the floating point number `3.2`.

Let's have a few more examples of valid conversions.

int to a float

`int a = 5;`

`float b;`

`b = a; `

Results in `b` holding a value ```5 ```in floating point format

float to a double

`float b = 10.3;`

`double c;`

`c = b;`

Results in `c` holding a value `10.3` in double format

Numeric type to a character

`int age = 65;`

`ch = age;`  // ch holds the value of 65

`cout << ch << endl;` // outputs the character `'A'` not the digits 65

The character `'A'` is ouput instead of 65 because this number is the ASCII code for the character `'A'`.

### Forcing type conversion

What if we specifically need to convert values from stronger type to a weaker.  We have seen that an error message will result if we try to get C++ to automatically do this for us.  So, how can we can force a type conversion?

We can cast the stronger type to a weaker type by using expression such as:-

`(int)`  forces conversion to an int

`(float)`  forces conversion to a float

`(double)`  forces conversion to a double

`(char)`  forces conversion to a char

Here is an example:-

float to an int

`int x; `

`double y = 3.2;`

`x =  (int) y;`

The (int) in parentheses forces the conversion.  Now we don't get an error message.  In effect, by using the casting statement we are informing C++ that we are intentionally converting a stronger type to a weaker and we are not just being idiots.  We should be aware that  information can be lost when we force type conversions.   In the above example, the decimal places are truncated: `x` ends up with a value of `3`.

int to a float

Sometimes you may have to convert a weaker datatype to a stronger one. If you divide one integer by another, you get an integer as a result.

`int i = 10;`

`cout << i/4 << endl;` // outputs --> 2

`cout << (float)i/4 << endl; `  //outputs --> 2.5

The (float) in parentheses forces the conversion of the integer 10 to 10.0.  Then the output of the division is also a float.

~Now try the activity~

 Activity E Given the declaration short int s = 65; int i; double d1, d2 = 5.2; char ch; For each of the following, state the final type and value of the operand on the left side of the =. d1 = (int) d2 + 10; i = (int) d2 * (char)10.34;ch = (char) (s + 3); Why not check your answers by using code.

## Extension Work

Carry out the following exercise:-

1. Start step7 of the practice assignment 3

That it!
Now try the quiz questions