Assignment Operators in C++
There are several different assignment operators in C Plus Plus (C++). All of them are used to form assignment expressions, which assign the value of an expression to an identifier.
The most commonly used assignment operator is =. Assignment expressions that make use of this operator are written in the form:
identifier = expression
where,
identifier
generally represents a variable, and
expression
represents a constant, a variable or a more complex expression.
Example:
a = 3; x = y; sum = a + b;
In the above statements, the first assignment expression causes the integer value 3 to assigned to the variable a
, and the second assignment causes the value of variable y
to be assigned to x
. In the third assignment, result in the value of the arithmetic expression is assigned to the variable sum
i.e., the value of a + b
is assigned to sum
.
Remember that the assignment operator = and the equality operator == are distinctly different. The assignment operator is used to assign a value to an identifier, whereas the equality operator is used to determine if two expressions have the same value. These operators cannot be used in place of one another.
Also, if the two operands in an assignment expression are of different data types, then the value of the expression on the right (i.e., the right hand operand) will automatically be converted to the type of the identifier on the left. The entire assignment expression will then be of this same data type.
Also, C++ contains the following five additional assignment operators: +=, -=,*=, /= and %=. To see how they are used, consider the first operator, +=.
The assignment expression:
expression 1 += expression 2
is equivalent to:
expression 1 = expression + expression 2
Similarly, the assignment expression:
expression 1 -= expression 2
is equivalent to:
expression 1 = expression - expression 2
and so on for all five operators.
Precedence of Assignment Operators:
Assignment operators have a lower precedence than any other operators that have been discussed so far. Therefore, unary operations, arithmetic operations, relational operations, equality operations and logical operations are all carried out before assignment operations. Moreover, the assignment operators have a right-to-left associativity.