Skip to content
HOME - C++ - What is the Assignment operator and Assignment Statement?

What is the Assignment operator and Assignment Statement?

c++

Assignment operator and Assignment Statement

The assignment operator is used to assign a value to a variable or a computational result to a variable. And the expression containing the assignment operator is called assignment statement. ‘ = ’ represents the assignment operator. It assigns the value or value of a variable to a variable from right to left. For example

Example 1

int a = 10 ; // 10 is assigned to a
int b = 20; // 20 is assigned to b
a = b; // b is assigned to a

In the above example b has value 20 which is assigned to a so a also has value 20 now.

Example 2

int a = 10, b = 20, sum =0;
sum = a + b;

The above line will compute the result of a + b first and then transfer the resultant value to the variable sum. So

Types of the assignment statement

There are two types of assignment operator
1. Simple assignment operator
2. Compound assignment operator

Simple Assignment statement

In a simple assignment operator, the value is written on the right side of the operator and the variable is on the left side of the operator. Writing a value to the left side causes a syntax error.
The general form of an assignment statement is

Variable = expression ;

Expression can be a constant value, variable, arithmetic, relational or logical expression. For example
a = 10;
a = b*c+a-b+7;

Compound assignment statement

Compound assignment statement is used to assign one value to more than one variables at a time.General form of compound statement is

Variable1 = variable2 = variable3 = – – – – – = variableN = value;

For example

int a, b , c;
a = b = c = 5;

In the above code, the value 5 is assigned to a,b and c at the same time.

Compound assignment operators

These operators are used to add, subtract, multiply or divide the to or from a variable. There are four compound assignment operators
+= for addition
-= for subtraction
*= for multiplication
/= for division

These above mentioned compound operators are used to increment or decrement the value of the variable by other than one.
General form of writing compound assignment expressions is

Variable operator= value;

For example

int a = 10, b = 20;

a += 5; or a = a+5;
It means In the above line the value of a is increased by 5 so the current value of a is 15.

b -= 5; or b = b-5;
In the above expression, the value of b is decremented by 5 and hence new value is 15.

a *= 7; or a = a*7;
In this case, the value is multiplied by 7 and the updated value is 70.

b /= 4; or b = b / 4;
In the above case, the value of b will become 5 i.e, 20 / 4 = 5.

Happy learning 🙂

You can read other relevant articles here.

Increment and decrement operator in c programming

What are an expression operators and operands in programming? 

What are the data types in programming languages?

Leave a Reply

Your email address will not be published.

en English
X