thumbnail

Assignment and compound assignment operators in Dart

Published on 29 March 2020
Last Updated on 29 March 2020

Assignment Operators

Refer to following table to know what arithmetic operators are do in Dart.

Operator Description
a = val Assign value of variable on the right side to variable on the left side
b ??= val Assign value to b if b is not null

Program that demonstrates use of Assignment Operators

main(List<String> args) {
  var val = 1;
  var x = val;
  print('x:${x} val:${val}');

  int y;
  // assign value to y if val is not null
  // because y is null, value of val is assigned to b
  y ??= val;
  print('y:${y} val:${val}');

  val = 20;
  // because y is non null, value of val will not be assigned to b
  y ??= val;
  print('y:${y} val:${val}');
}

Above program produces following output:

x:1 val:1
y:1 val:1
y:1 val:20

Compound Assignment Operators

Operator Meaning Description
a –= b a = a – b Assign result of a - b to a
a /= b a = a / b Assign result of a / b to a
a %= b a = a % b Assign result of a % b to a
a »= b a = a » b Assign result of a » b to a
a ^= b a = a ^ b Assign result of a ^ b to a
a += b a = a + b Assign result of a + b to a
a *= b a = a * b Assign result of a * b to a
a ~/= b a = a ~/ b Assign result of a ~/ b to a
a «= b a = a « b Assign result of a « b to a
a &= b a = a & b Assign result of a & b to a
a |= b a = a | b Assign result of a | b to a

Program using Compound Arithmetic Operators

// Program that demonstrates use of compound arithmetic operators
main(List<String> args) {
  double a = 1.0, b = 2.0;
  // operators that work well with double
  a = 1.0;
  b = 2.0;
  a -= b;
  print('a:${a}');

  a = 1.0;
  b = 2.0;
  a /= b;
  print('a:${a}');

  a = 1.0;
  b = 2.0;
  a %= b;
  print('a:${a}');

  a = 1.0;
  b = 2.0;
  a += b;
  print('a:${a}');

  a = 1.0;
  b = 2.0;
  a *= b;
  print('a:${a}');

  // operators that work well with int
  int x = 1, y = 2;
  x >>= y;
  print('x:${x}');

  x = 1;
  y = 2;
  x ^= y;
  print('x:${x}');

  x = 1;
  y = 2;
  x <<= y;
  print('x:${x}');

  x = 1;
  y = 2;
  x &= y;
  print('x:${x}');

  x = 1;
  y = 2;
  x |= y;
  print('x:${x}');

  x = 1;
  y = 2;
  x ~/= y;
  print('x:${x}');
}

Above program produces following output:

a:-1.0
a:0.5
a:1.0
a:3.0
a:2.0
x:0
x:3
x:4
x:0
x:3
x:0

We hope that you found this guide useful while learning how to use arithmetic operators in Dart.