DEV Community

Mehfila A Parkkulthil
Mehfila A Parkkulthil

Posted on

Day 6: C++ Language | Assignment operators

Assignment Operators

Assignment operators are used to assign values to variables. The most basic form is the simple assignment operator =.

Syntax: variable = value;

Purpose: Assigns the value on the right to the variable on the left.

Example:
int a = 5;  
Assigns the value 5 to variable a.

Enter fullscreen mode Exit fullscreen mode

Compound Assignment Operators

Compound assignment operators perform an operation and assign the result to the variable in one step.
Here are some:

Addition Assignment (+=)

Adds the value on the right to the variable on the left and assigns the result to the variable.

Syntax: variable += value;

Example:
int a = 5;
a += 3; 
a += 3 is equivalent to a = a + 3;  
Then a becomes 8 (ie, a = 5+3).
Enter fullscreen mode Exit fullscreen mode

Subtraction Assignment (-=)

Subtracts the value on the right from the variable on the left and assigns the result to the variable.

Syntax: variable -= value;

Example:
int a = 5;
a -= 2; 
a -=2 is equivalent to a = a - 2;  
Then a becomes 3 ( ie, a= 5-2).
Enter fullscreen mode Exit fullscreen mode

Multiplication Assignment (*=)

Multiplies the variable on the left by the value on the right and assigns the result to the variable.

Syntax: variable *= value;

Example:
int a = 5;
a *= 4;  // Equivalent to a = a * 4;  // a becomes 20

Enter fullscreen mode Exit fullscreen mode

Division Assignment (/=)

Divides the variable on the left by the value on the right and assigns the result to the variable.

Syntax: variable /= value;

Example:
int a = 20;
a /= 4;  // Equivalent to a = a / 4;  // a becomes 5

Enter fullscreen mode Exit fullscreen mode

Modulus Assignment (%=)

Assigns the remainder of the division of the variable on the left by the value on the right to the variable.

Syntax: variable %= value;


Example:
int a = 10;
a %= 3;  // Equivalent to a = a % 3;  // a becomes 1 (remainder of 10 / 3)

Enter fullscreen mode Exit fullscreen mode

Previous Blog

Top comments (0)

Eliminate Context Switching and Maximize Productivity

Pieces.app

Pieces Copilot is your personalized workflow assistant, working alongside your favorite apps. Ask questions about entire repositories, generate contextualized code, save and reuse useful snippets, and streamline your development process.

Learn more