C++ Assignment Operator

C++ assignment Operator basics

  1. Assignment Operator is used to assign value to an variable.
  2. Assignment Operator is denoted by equal to (=) sign.
  3. This operator copies the value at the right side of the operator into the left side variable.
  4. Assignment Operator is binary operator.
  5. Assignment Operator has higher precedence than comma operator only.
  6. Assignment Operator has lower precedence than all other operators except comma operator.

Ways of Using Assignment Operator:

In this section we are going to see different ways in which Assignment Operator can be used.

Assignment Operator used to Assign Value

In this case the particular value or result of particular expression is assigned to the variable.

#include<iostream>
using namespace std;
int main()
{
   int value;
   value=10;
   return 0;
}

In this example, 10 is assigned to variable value.

Assignment Operator used to Type Cast

#include<iostream>
using namespace std;
int main()
{
   int value;
   value=10.5;
   cout<<value;
   return 0;
}

Higher values can be type cast to lower values using assignment operator. It can also cast lower values to higher values.

Shorthand assignment operator:

Operator Symbol Name of OperatorExample Equivalent Construct
+=Addition assignment a+=5 a=a+5
-=Subtraction assignment a-=5 a=a-5
*=Multiplication assignment a*=5 a=a*5
/=Division assignment a/=5 a=a/5
%=Remainder assignment a%=5 a=a%5
Example:

#include <iostream>
using namespace std;
int main()
{
   int num = 10;
   num+=5 ;
   cout << "Result of Expression 1 = " <<num<< endl ;
   num = 10;
   num-=5 ;
   cout << "Result of Expression 2 = " <<num<< endl ;
   num = 10;
   num*=5 ;
   cout << "Result of Expression 3 = " <<num<< endl ;
   num = 10;
   num/=5 ;
   cout << "Result of Expression 4 = " <<num<< endl ;
   num = 10;
   num%=5 ;
   cout << "Result of Expression 5 = " <<num<< endl ;
   return 0;
}


Output:

Result of Expression 1 = 15
Result of Expression 2 = 5
Result of Expression 3 = 50
Result of Expression 4 = 2
Result of Expression 5 = 0