Assignment operators in C++ | Shorthand operators in C++

Assignment operators in C++ | Shorthand operators in C++



Assignment operators in C++ are also known as shorthand operators in C++. They are used to update the existing value of a variable in an easy way. Various Assignment operators in C++ are:

i. =

It is used to assign some value to a variable.

Example:

n=10

ii. +=

It adds some value to the existing value of a variable.

Example

n=10

n+=3  #n=10+3 =13

n becomes 13

iii. -=

It subtracts some value from existing value of a variable.

Example

n=10

n-=3  #n=10-3 =7

n becomes 7

iv. *=

it multiplies existing value of a numeric variable by another value.

Example

n=10

n*=3  #n=10*3 =30

n becomes 30

v. /=

it divides existing value of a numeric variable by another value.

Example

n=10

n/=3  #n=10/3 =3.33333333

n becomes 3.33333333

vi. //=

it divides existing value of a numeric variable by another value and finds quotient without any digit after decimal point.

Example

n=10

n//=3  #n=10//3 =3

n becomes 3

vii. %=

it divides existing value of a numeric variable by another value and find remainder.

Example

n=10

n%=3  #n=10%3 =1

n becomes 1

viii. &=

Applies bitwise AND operator on existing value of a numeric variable along with another value .

Example

n=10

n&=7  #n=10&7 =2

n becomes 2

ix. |=

Applies bitwise OR operator on existing value of a numeric variable along with another value .

Example

n=10

n|=7  #n=10|7 =15

n becomes 15

x. ^=

Applies bitwise XOR operator on existing value of a numeric variable along with another value .

Example

n=10

n^=7  #n=10^7 =13

n becomes 13

xi. <<=

Applies bitwise LEFT SHIFT operator on existing value of a numeric variable.

Example

n=10

n<<=1  #n=10<<1 =20

n becomes 20

xi. >>=

Applies bitwise RIGHT SHIFT operator on existing value of a numeric variable.

Example

n=10

n>>=1  #n=10>>1 =5

n becomes 5

//Program to demonstrate the use of shorthand operators.

#include<iostream> 
using namespace std;
int main()
{
  int n=10;
  n+=5;
  cout<<”\n n+=5 =”<<n;
  n-=3;
  cout<<”\n n-=3 =”<<n;
  n*=3;
  cout<<”\n n*=3 = ”<<n;
  n/=2;
  cout<<”\n n/=2 =”<<n;
  n%=3;
  cout<<”\n n%=3 =”<<n;
  return 0;
}

Output

n+=5 = 15
n-=3 = 12 
n*=3 = 36 
n/=2 = 18
n%=3 = 0



Spread the love
Lesson tags: assignment operators in C, shorthand operators in C
Back to: C++ Programming Notes
Spread the love