Assignment operators in Dart Programming

Dart ProgrammingServer Side ProgrammingProgramming

We make use of assignment operators whenever we want to assign values to a variable. There are times when we combine assignment operators with arithmetic operators and logical operators to build a shorthand version of both the assignment and arithmetic (or logical) expression. These shorthand versions are also known as compound statements.

In the table below, all the assignment operators that are present in dart are mentioned.

Consider the table shown below −

OperatorDescriptionExpression
=Assignment operatora = b
+=Add and assign combineda += b is equivalent to a = a + b
-=Subtract and assigna –= b is equivalent to a = a - b
*=Multiply and assigna *= b is equivalent to a = a * b
/=Divide and assigna /= b is equivalent to a = a / b
~/=Divide and assign and store Int valuea ~/= b is equivalent to a = a ~/ b
%=Modulus and assigna %= b is equivalent to a = a % b
<<=Left shift and and assigna <<= 3 is equivalent to a = a << 3
>>=Right shift and assigna >>= 3 is equivalent to a = a >> 3
&=Bitwise AND assigna &= 3 is equivalent to a = a & 3
^=Bitwise exclusive OR and assigna ^= 3 is equivalent to a = a ^ 3
|=Bitwise inclusive OR and assigna |= 3 is equivalent to a = a | 3

Let's make use of all the above mentioned assignment operators in a dart program.

Example

Consider the example shown below −

 Live Demo

void main(){
   var x = 10;
   print("x = 10 -> ${x}");

   x += 15;
   print("x += 15 -> ${x}");

   x -= 10;
   print("x -= 10 -> ${x}");

   x *= 10;
   print("x *= 10 -> ${x}");

   x ~/= 5;
   print("x /= 5 -> ${x}");

   x %= 7;
   print("x %= 7 -> ${x}");

   x <<= 2;
   print("x <<= 2 -> ${x}");

   x >>= 3;
   print("x >>= 3 -> ${x}");

   x &= 2;
   print("x &= 2 -> ${x}");

   x ^= 5;
   print("x ^= 5 -> ${x}");

   x |= 10;
   print("x |= 10 -> ${x}");
}

Output

x = 10 -> 10
x += 15 -> 25
x -= 10 -> 15
x *= 10 -> 150
x /= 5 -> 30
x %= 7 -> 2
x <<= 2 -> 8
x >>= 3 -> 1
x &= 2 -> 0
x ^= 5 -> 5
x |= 10 -> 15
raja
Published on 21-May-2021 12:14:43
Advertisements