# Cpp - Operator Assignment Operator

## Introduction

An assignment statement uses the assignment operator = to assign a value to an expression.

The variable must be placed on the left and the assigned value on the right of the assignment operator.

```z = 7.5;
y = z;
x = 2.0 + 4.2 * z;
```

Each assignment is an expression in its own right, and its value is the value assigned.

```sin(x = 2.5);
```

In the above assignment the number 2.5 is assigned to x and then passed to the function as an argument.

Multiple assignments are evaluated from right to left.

```i = j = 9;
```

In this case the value 9 is first assigned to j and then to i.

## Compound Assignments

Compound assignment operators perform an arithmetic operation and an assignment, for example.

```i += 3;
```

is equivalent to

```i = i + 3;
```

i *= j + 2; is equivalent to

```i = i * (j+2);
```

The second example shows that compound assignments are implicitly placed in parentheses.

The precedence of the compound assignment is as low as that of the simple assignment.

Compound assignment operators can be composed from any binary arithmetic operator and with bit operators.

The following compound operators are thus available: +=, -=, *=, /=, and %=.

## Demo

```#include <iostream>
#include <iomanip>
using namespace std;

int main() /*from   w  ww  .  j a v a 2s  .  c  o m*/
{
float x, y;

cout << "\n Please enter a starting value:    ";
cin >> x;

cout << "\n Please enter the increment value: ";
cin >> y;

x += y;

cout << "\n And now multiplication! ";
cout << "\n Please enter a factor:  ";
cin >> y;

x *= y;

cout << "\n Finally division.";
cout << "\n Please supply a divisor: ";
cin >> y;

x /= y;

cout << "\n And this is "
<< "your current lucky number: "
// without digits after the decimal point:
<< fixed << setprecision(0)
<< x << endl;

return 0;
}
```

## Result An expression consists of an assignment operator, an operand to its left called an l-value, and an operand to its right called an r-value.

In the expression grade = 95, the l-value is grade, and the r-value is 95.

Constants are r-values but cannot be l-values.

## Demo

```#include <iostream>
int main() //from  ww  w  .j  a  v  a 2s .  co  m
{
int x = 1, y = 4, z = 8;
std::cout << "Before -- x: " << x << " y: " << y;
std::cout << " z: " << z << "\n\n";
z = x = y + 13;
std::cout << "After -- x: " << x << " y: " << y;
std::cout << " z: " << z << "\n";
return 0;
}
```

## Result 