Arithmetic operators

Dart supports the usual arithmetic operators, as shown in the following table.

OperatorMeaning
+Add
Subtract
-exprUnary minus, also known as negation (reverse the sign of the expression)
*Multiply
/Divide
~/Divide, returning an integer result
%Get the remainder of an integer division (modulo)

Example:

  1. assert(2 + 3 == 5);
  2. assert(2 - 3 == -1);
  3. assert(2 * 3 == 6);
  4. assert(5 / 2 == 2.5); // Result is a double
  5. assert(5 ~/ 2 == 2); // Result is an int
  6. assert(5 % 2 == 1); // Remainder
  7. assert('5/2 = ${5 ~/ 2} r ${5 % 2}' == '5/2 = 2 r 1');

Dart also supports both prefix and postfix increment and decrementoperators.

OperatorMeaning
++varvar = var + 1 (expression value is var + 1)
var++var = var + 1 (expression value is var)
varvar = var – 1 (expression value is var – 1)
varvar = var – 1 (expression value is var)

Example:

  1. var a, b;
  2. a = 0;
  3. b = ++a; // Increment a before b gets its value.
  4. assert(a == b); // 1 == 1
  5. a = 0;
  6. b = a++; // Increment a AFTER b gets its value.
  7. assert(a != b); // 1 != 0
  8. a = 0;
  9. b = --a; // Decrement a before b gets its value.
  10. assert(a == b); // -1 == -1
  11. a = 0;
  12. b = a--; // Decrement a AFTER b gets its value.
  13. assert(a != b); // -1 != 0