Assignment And Arithmetic Operators
The assignment operator allows assigning a value to a variable or in general an lvalue (an entity that can appear on the left side of
the assignment operator).
Most of the times such entity will be a variable, but it might also be a function returning a reference for example. The value
being assigned, which can be represented by an expression or an entity’s value, is called rvalue. In the first line of code below,
a is the lvalue, while 3 is the rvalue. In the second line, b is the lvalue, a is the rvalue.
int a = 3; // a: lvalue. 3 rvalue
int b = a; // b: lvalue. a rvalue
Several occurrences of the assignment operator can appear in a statement, causing the same rvalue to be assigned to more than one lvalue:
b = a = 45;
The operators for adding, subtracting, multiplying and dividing are
+ - * -
which can be intermixed with parentheses. Also, notice that if two types are present within an expression, the overall expression
result turns out to be of the "largest" type. So if you add an
int to a
float
, the result will be a
float.
The increment and decrement operators are
++ --
and they can be applied as prefixes or suffixes.
The operator
++ as a suffix increases its operand by one unit. Such increase takes place after any
assignment operations having the
++’s operand as an rvalue:
int h = 5;
int i = h++;
after the two statements above,
i's value is 5, while
h's is 6.
On the other hand, the
++ operator as a prefix increases its operand by one unit first before any assignment operations having
++'s operand as an rvalue:
int h1 = 5;
int j = ++h1;
after the two statements above,
j’s value is 6, and
h1’s is 6.
Dually, the
–- operator decreases its operand and, as seen for
++,
it is applied after its operand is assigned if it is postponed, while it is applied before if it comes before the operand.
Example
#include <iostream>
using namespace std;
int main()
{
int a = 3; // a: lvalue. 3 rvalue
cout << "a: " << a << endl;
int b = a;
cout << "b: " << b << endl;
b = a = 45;
cout << "a and then b: " << a << " " << b << endl;
int d = 2 + 3;
cout << "d: " << d << endl;
int e = 23 - 10;
cout << "e: " << e << endl;
int g = 2 * 8;
cout << "g: " << g << endl;
int h = 20 / 4;
cout << "h: " << h << endl;
h++;
cout << "h: " << h << endl;
++h;
cout << "h: " << h << endl;
int i = h++;
cout << "i: " << i << endl;
i = ++h;
cout << "i: " << i << endl;
int j = 12 % 5;
cout << "j: " << j << endl;
}
Output
a: 3
b: 3
a and then b: 45 45
d: 5
e: 13
g: 16
h: 5
h: 6
h: 7
i: 7
i: 9
j: 2