Operators: Assignment Operator ( )
Operators: Assignment Operator ( )
Once introduced to variables and constants, we can begin to operate with them by
using operators. What follows is a complete list of operators. At this point, it is likely not
necessary to know all of them, but they are all listed here to also serve as reference.
Assignment operator (=)
The assignment operator assigns a value to a variable.
x = 5;
This statement assigns the integer value 5 to the variable x. The assignment operation always
takes place from right to left, and never the other way around:
x = y;
This statement assigns to variable x the value contained in variable y. The value of x at the
moment this statement is executed is lost and replaced by the value of y.
Consider also that we are only assigning the value of y to x at the moment of the assignment
operation. Therefore, if y changes at a later moment, it will not affect the new value taken by x.
For example, let's have a look at the following code - I have included the evolution of the content
stored in the variables as comments:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// assignment operator
#include <iostream>
using namespace std;
int main ()
{
int a, b; // a:?, b:?
a = 10; // a:10, b:?
b = 4; // a:10, b:4
a = b; // a:4, b:4
b = 7; // a:4, b:7
cout << "a:";
cout << a;
cout << " b:";
cout << b;
}
a:4 b:7
This program prints on screen the final values of a and b (4 and 7, respectively). Notice
how a was not affected by the final modification of b, even though we declared a = b earlier.
Assignment operations are expressions that can be evaluated. That means that the assignment
itself has a value, and -for fundamental types- this value is the one assigned in the operation. For
example:
y = 2 + (x = 5);
In this expression, y is assigned the result of adding 2 and the value of another assignment
expression (which has itself a value of 5). It is roughly equivalent to:
1
2
x = 5;
y = 2 + x;
With the final result of assigning 7 to y.
The following expression is also valid in C++:
x = y = z = 5;
It assigns 5 to the all three variables: x, y and z; always from right-to-left.